Iterar a través de las opciones <select>
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.
Aceptado
$("#selectId > option").each(function() {
alert(this.text + ' ' + this.value);
});
- http://api.jquery.com/each/
- http://jsfiddle.net/Rx3AP/
Esto funcionó para mí
$(function() {
$("#select option").each(function(i){
alert($(this).text() + " : " + $(this).val());
});
});
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);
});
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
}