option element of a select selected by default

2

I have a select with a single fixed option disabled, the other options are added after an ajax query, I need to load the page to select the fixed option with the disable.

<select id="desdeReserveInput" name="desde" class="form-control">
      <option value="lugar" selected disabled>Lugar</option>
</select>

Here is the jquery that adds the other options:

lugares.forEach(function (item) {                
      var desdeOption = document.createElement('option');
      desdeOption.value = item['nombre'];
      desdeOption.innerHTML = item['nombre'];
      desde.appendChild(desdeOption);          
});

Again, the only difficulty I have is that when the page is loaded the first option that I added with jquery is automatically selected.

    
asked by Armando Rodríguez Acosta 28.11.2018 в 17:27
source

1 answer

3

Your problem is that you do not assign the value of select at any time.

You have to use the property value

I leave you a small example

var select = document.getElementById('test')
//Loop para agregar datos para ejemplificar
for(var i = 0; i<10; i++)
{
  var opcion =  document.createElement('option');
  opcion.value = "item "+i;
  opcion.innerHTML = "item "+i;
  select.appendChild(opcion);          
}

//Asigno el valor "defecto" a el objeto select (por lo que automáticamente se selecciona la opción son dicho value
select.value = "defecto";
<select name="" id="test">
   <option value="defecto" disabled>Valor por defecto</option>      
</select>
    
answered by 28.11.2018 / 17:35
source