Zoolander
Zoolander

Reputation: 2363

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.

Upvotes: 5

Views: 31051

Answers (9)

Darkosphere
Darkosphere

Reputation: 161

You could use this short function to do that:

function findIndexfromOptionName( select, optionName ) {
    let options = Array.from( select.options );
    return options.findIndex( (opt) => opt.label == optionName );
}

Arguments:

  • select: an HTMLSelect element
  • optionName: as a string

Explanation:
On the first line of the function body we retrieve the <select> options as an array using Array.from(). This allow us to use Array.prototype.findIndex() to return the index of the first option that match the provided name, if any or return -1 if there is no match.

Want some reasons to use it ?
It has a short implementation and the semantic is pretty clear. Also pure JS.

Upvotes: 4

Incognito
Incognito

Reputation: 20765

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

Upvotes: 6

jimbo
jimbo

Reputation: 11042

[edit - expanded to include non-jquery method]

I strongly recommend using jQuery for this since the solution is a one-liner:

jQuery('#names option:contains("Max")').val()

However, here's a pure JavaScript implementation anyway:

function findOption( select, matchMe ) {

  var

    // list of child options
    options = select.getElementsByTagName('option'),

    // iteration vars
    i = options.length,
    text,
    option;

  while (i--) {

    option = options[i];
    text = option.textContent || option.innerText || '';

    // (optional) add additional processing to text, such as trimming whitespace
    text = text.replace(/^\s+|\s+$/g);

    if (text === matchMe) {
      return option.getAttribute('value');
    }

  }

  return null;

}

Example usage:

alert(
  findOption(
    document.getElementsByTagName('select')[0],
    "Max"
  )
);

Alerts 3

Upvotes: 0

Brian Colvin
Brian Colvin

Reputation: 380

var x = document.getElementById("names");
for(var i = 0; i<x.options.length; i++){
    if("Max" == x.options[i].text){
        doSomething();
        //maybe x.selectedIndex = i;
    }
}

Upvotes: 0

Dennis
Dennis

Reputation: 32598

The options property stores the options in a select menu - iterate over it and compare the contents.

var list = document.getElementById("names").options;

for(var i = 0; i<list.length; i++){
    if(list[i].text== "Max") { //Compare
        list[i].selected = true; //Select the option.
    }
}

JSFiddle: http://jsfiddle.net/cuTxu/2

Upvotes: 1

karim79
karim79

Reputation: 342635

var opts = document.getElementById("names").options;
for(var i = 0; i < opts.length; i++) {
    if(opts[i].innerText == "Max") {
        alert("found it at index " + i + " or number " + (i + 1));
        break;
    }
}

Demo.

Upvotes: 3

topek
topek

Reputation: 18979

This should do the trick:

var options = document.getElementsByTagName('select')[0].children,
    i,
    l = options.length,
    index;

for(i = 0; i < l; i++){
  if(options[i].firstChild.nodeValue === 'Max'){index = i};
}

Please note that the index is zero based, what mean it is one less than you would expect.

Upvotes: 0

Einacio
Einacio

Reputation: 3532

in PLAIN js

var sel, opts, opt, x, txt;
txt='Max';
sel=document.getElementById('names');
opts=sel.options;
for (x=0;x<opts.lenght;x++){
    if (opts[x].text === txt){
        opt=opts[x];
    }
}

Upvotes: 1

ipr101
ipr101

Reputation: 24236

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

Upvotes: 6

Related Questions