Selecting an option element from a dropdown by its

2019-02-13 09:13发布

问题:

Given an HTML form element like:

<select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>

I know I can select the first option with

document.getElementById("mydropdown").value='foo'

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

回答1:

var desiredValue = "eggs"
var el = document.getElementById("mydropdown");
for(var i=0; i<el.options.length; i++) {
  if ( el.options[i].text == desiredValue ) {
    el.selectedIndex = i;
    break;
  }
}


回答2:

I'd use the selectedIndex or a loop to select the option by text, the code below doesn't work.

document.getElementById("mydropdown").text = 'Eggs';


回答3:

If you want to get an option by its innertext and not by the value you can do this:

function go(){
    var dropdown = document.getElementById('mydropdown');
    var textSelected = 'Spam';

    for(var i=0, max=dropdown.children.length; i<max; i++) {
        if(textSelected == dropdown.children[i].innerHTML){
            alert(textSelected);
            return;
        }
    }
}


回答4:

Older IE does not handle options of a select as child nodes, but all browsers implement the text property of a select's option collection.

function selectbytext(sel, txt){
    if(typeof sel== 'string'){
        sel= document.getELementById(sel) || document.getELementsByName(sel)[0];
    }
    var opts= sel.options;
    for(var i= 0, L= opts.length; i<L; i++){
        if(opts[i].text== txt){
            sel.selectedIndex= i;
            break;
        }
    }
    return i;
}