Iterate through
Advertisement
Iterate through
Question
I have a <select>
element in HTML. This element represents a drop down list. I'm trying to understand how to iterate through the options in the <select>
element via JQuery.
How do I use JQuery to display the value and text of each option in a <select>
element? I just want to display them in an alert()
box.
2014/08/18
Accepted Answer
$("#selectId > option").each(function() {
alert(this.text + ' ' + this.value);
});
2010/06/01
Read more... Read less...
This worked for me
$(function() {
$("#select option").each(function(i){
alert($(this).text() + " : " + $(this).val());
});
});
2012/05/04
can also Use parameterized each with index and the element.
$('#selectIntegrationConf').find('option').each(function(index,element){
console.log(index);
console.log(element.value);
console.log(element.text);
});
// this will also work
$('#selectIntegrationConf option').each(function(index,element){
console.log(index);
console.log(element.value);
console.log(element.text);
});
2014/11/19
And the requisite, non-jquery way, for followers, since google seems to send everyone here:
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
}
2017/11/14
You can try like this too.
Your HTML
Code
<select id="mySelectionBox">
<option value="hello">Foo</option>
<option value="hello1">Foo1</option>
<option value="hello2">Foo2</option>
<option value="hello3">Foo3</option>
</select>
You JQuery
Code
$("#mySelectionBox option").each(function() {
alert(this.text + ' ' + this.value);
});
OR
var select = $('#mySelectionBox')[0];
for (var i = 0; i < select.length; i++){
var option = select.options[i];
alert (option.text + ' ' + option.value);
}
2018/05/15
If you don't want Jquery (and can use ES6)
for (const option of document.getElementById('mySelect')) {
console.log(option);
}
2019/03/11
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]