Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 454
Zoolander Avatar asked Dec 12 '22 09:12

Zoolander


1 Answers

http://jsfiddle.net/x8f7g/1/

You want to select the element, iterate over the array, find the text value, and return the index.

  • Don't use InnerHTML, it's slow and breaks and not standards compliant
  • Dont use innerText, simmilar reasons but not quite as serious
  • Do use a function so you can do it all over again.
  • Do select the child text node, and retreives the nodeValue, which is cross-browser friendly

Example:

function indexMatchingText(ele, text) {
    for (var i=0; i<ele.length;i++) {
        if (ele[i].childNodes[0].nodeValue === text){
            return i;
        }
    }
    return undefined;
}
like image 108
Incognito Avatar answered Mar 08 '23 23:03

Incognito