Iterar a través de las opciones <select>

Resuelto user208662 asked hace 14 años • 9 respuestas

Tengo un <select>elemento en HTML. Este elemento representa una lista desplegable. Estoy tratando de entender cómo iterar a través de las opciones del <select>elemento a través de JQuery.

¿Cómo uso JQuery para mostrar el valor y el texto de cada opción en un <select>elemento? Sólo quiero mostrarlos en una alert()caja.

user208662 avatar Jun 01 '10 20:06 user208662
Aceptado
$("#selectId > option").each(function() {
    alert(this.text + ' ' + this.value);
});
  • http://api.jquery.com/each/
  • http://jsfiddle.net/Rx3AP/
karim79 avatar Jun 01 '2010 13:06 karim79

Esto funcionó para mí

$(function() {
    $("#select option").each(function(i){
        alert($(this).text() + " : " + $(this).val());
    });
});
IT ppl avatar May 04 '2012 06:05 IT ppl

También se puede utilizar parametrizado cada uno con el índice y el elemento.

$('#selectIntegrationConf').find('option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });

// esto también funcionará

$('#selectIntegrationConf option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });
Arun Pratap Singh avatar Nov 19 '2014 06:11 Arun Pratap Singh

Y la forma requerida, sin jquery, para los seguidores, ya que Google parece enviar a todos aquí:

  var select = document.getElementById("select_id");
  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    // now have option.text, option.value
  }
rogerdpack avatar Apr 07 '2017 21:04 rogerdpack