简体   繁体   中英

How to check if a select field has a certain option value without jQuery

How do you check if an option with a particular value exists in a select field?

<select>
  <option value="o1">Option 1</option>
  <option value="o2">Option 2</option>
</select>

If select has value "o1" = true

If select has value "o4" = false

If you'll add an id field to the select, say id="selector" you can do:

var x = document.getElementById("selector").options;
for(var i=0; i<x.length; i++){
    if (x[i].value == "o1"){
    ...

etc.

You can loop over the options and check their values:

var select = document.getElementById('selectID') || 
             document.forms[formName or index].elements[selectName or index];
var options = select.options

for (var i=0, iLen=options.length; i<iLen; i++) {
  if (options[i].value == 'foo') {
    // found option with value 'foo'
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM