I have a select menu and I need to dynamically select the option based on the text value of the option element. For example, my select looks like this:
<select id="names">
<option value="">Please Select</option>
<option value="1">John</option>
<option value="2">Steve</option>
<option value="3">Max</option>
</select>
If I have the string "Max", how can I get that the index of the option is 4 so I can dynamically set this as the selectedIndex with JavaScript?
No jQuery.
http://jsfiddle.net/x8f7g/1/
You want to select the element, iterate over the array, find the text value, and return the index.
Example:
function indexMatchingText(ele, text) {
for (var i=0; i<ele.length;i++) {
if (ele[i].childNodes[0].nodeValue === text){
return i;
}
}
return undefined;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With