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.
Try this, it should find and then select the relevant option in the select box.
var searchtext = "max";
for (var i = 0; i < listbox.options.length; ++i) {
if (listbox.options[i].text === searchtext) listbox.options[i].selected = true;
}