Default value to select with a javascript function

0

How can I set the default value with a javascript function?

<select id='tipoDocumento' 
  name='tipoDocumento' class='select2-container select2me form-control'>
<option value=''>Seleccionar</option>
<?php
foreach ($tipoDocumento as $i=>$descripcion){
  if ($_POST['tipoDocumento']==$i){
    echo "<option value ='" . $i ."'selected>". $descripcion ."</option>";
  }else{
    echo "<option value ='" . $i ."'>". $descripcion ."</option>";
  }
}
?>
</select>

The select I fill it with data from a base that I have, but I can not put with a button that in the onclick call a function, the value of Select as when the page is just loaded.

Thank you very much!

    
asked by Fede 09.08.2018 в 23:47
source

3 answers

0

You just have to save the original value in a variable and reset it when the button is pressed. Something like this:

var valor = document.getElementById("tipoDocumento").value;
function resetear() {
  document.getElementById("tipoDocumento").value = valor;
}
<select id='tipoDocumento' 
  name='tipoDocumento' class='select2-container select2me form-control'>
<option value=''>Seleccionar</option>
<option value='1'>carta</option>
<option value='2' selected>foto</option>
</select>
<button id="reset" onClick="resetear();">Resetear</button>
    
answered by 09.08.2018 в 23:58
0

you can add this'

<body onload="funcion()">

' the function is executed each time you reload the page without putting a button!

    
answered by 10.08.2018 в 00:00
0

What you can do is save the id of the selected item when loading the page:

foreach ($tipoDocumento as $i=>$descripcion){
  if ($_POST['tipoDocumento']==$i){
    echo "<option value ='" . $i ."'selected>". $descripcion ."</option>";
    $seleccionado = $i;
  }else{
    echo "<option value ='" . $i ."'>". $descripcion ."</option>";
  }
}

Then in a javascript you can create a function to load the initial value to the select:

<script>
  function cambiarSeleccionado () {
    var seleccionado = <?php echo $seleccionado ?>;
    document.getElementById('tipoDocumento').value = seleccionado;
  }
</script>

This function can be ordered by calling from a button on the onclick. I leave the link of the example php. Example

    
answered by 10.08.2018 в 00:03