Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
Can't set selected option from JavaScript

I have a problem when trying to set selected option from javascript. I created one select and added options with php from mysql like this:

<select class="form-control input-group-lg" name="progress" id="progress">
<?php
  if ($conn === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
  }

  $sql = "SELECT * FROM progress";
  if ($result = mysqli_query($conn, $sql)) {
    if (mysqli_num_rows($result) > 0) {
      while ($row = mysqli_fetch_array($result)) {
        $id = $row['id'];
        $progress_name = $row['name'];
        echo "<option>$progress_name</option>";
      }
    }
    else {
      echo "<option>Fault!</option>";
    }
  }
  else {
    echo "$sql. " . mysqli_error($conn);
  }
  mysqli_close($conn);
?>
</select>

And then set selected option from javascript like this:

$('#progress').val("Value to set");

This method works fine and it sets selected option with that value which I want.

ANOTHER METHOD:

I have php file and I select data from database (MySQL) in json and then using ajax like this

$.ajax({
  url: 'data_control/orders/progress_select.php',
  type: 'get',
  method: "POST",
  data: {selected_value:selected_value},
  dataType: 'JSON',
  success: function (response) {
    var len = response.length;
    for (var i = 0; i < len; i++) {
      var progress_name = response[i].progress_name;
      var option = document.createElement("option");
      option.text = progress_name;
      option.value = progress_name;
      var select = document.getElementById('progress');
      select.appendChild(option);
    }
  }
});

Options are added successfully, but I can't set selected value in this way:

$('#progress').val("Value to set");

Thanks for help!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You cannot set the value outside the success

Either do

var select = document.getElementById('progress');
for (var i = 0; i < len; i++) {
  var progress_name = response[i].progress_name;
  var option = document.createElement("option");
  option.text = progress_name;
  option.value = progress_name;
  select.appendChild(option);
}
select.value='Value to set'

OR

var select = document.getElementById('progress');
for (var i = 0; i < len; i++) {
  var progress_name = response[i].progress_name;
  var option = document.createElement("option");
  option.text = progress_name;
  option.value = progress_name;
  if (progress_name==='Value to set') options.selected = true;
  select.appendChild(option);
}

Shorter alternative

document.getElementById('progress').innerHTML = response
 .map(({progress_name}) => `<option${progress_name === 'Value to set'?' selected' : ''} value="${progress_name}">${progress_name}</option>`)
 .join("")
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda