【问题标题】:How to check if a select field has a certain option value without jQuery如何在没有jQuery的情况下检查选择字段是否具有某个选项值
【发布时间】:2013-07-31 22:13:17
【问题描述】:

如何检查选择字段中是否存在具有特定值的选项?

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

如果选择的值为 "o1" = true

如果选择的值为 "o4" = false

【问题讨论】:

  • 获取对选择元素的引用。它有一个 options 属性,它是所有选项的集合。 For 循环遍历它们。检查它们的值。

标签: javascript option exists


【解决方案1】:

您可以遍历选项并检查它们的值:

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

【讨论】:

  • 可能想在if 块的末尾添加一个break;?无论哪种方式,答案都很好:) 也许querySelector(All) 的使用也很有用
【解决方案2】:

如果您将id 字段添加到选择中,例如id="selector",您可以这样做:

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

等等

【讨论】:

  • OP 没有提及检查其selected 状态
  • 没问题。那么现在你可能想要显示循环而不是硬编码[0](即使你有“等”)
猜你喜欢
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
  • 2016-09-07
  • 2015-12-17
相关资源
最近更新 更多