How to get the index of an option in a select menu by matching the text with plain Javascript?

Zoolander picture Zoolander · Sep 20, 2011 · Viewed 18.3k times · Source

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.

Answer

ipr101 picture ipr101 · Sep 20, 2011

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;
}