2013-07-31 66 views
0

如何檢查選擇字段中是否存在具有特定值的選項?如何在沒有jQuery的情況下檢查選擇字段是否具有特定選項值

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

如果選擇具有值「01」 =真

如果選擇具有價值「O4」 =假

+1

獲取select元素的引用。它有一個選項屬性,它是所有選項的集合。通過它們循環。檢查它們的值。 – 2013-07-31 22:16:18

回答

1

你也可以遍歷的OPTIO NS和檢查它們的值:

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

可能想要在'if'塊尾部添加一個'break;'?無論哪種方式,很好的答案:)也許使用'querySelector(全部)'也可能有用 – Ian

1

如果你的id字段添加到選擇,說id="selector"你可以做:

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

+0

OP沒有提到檢查其「選定」狀態 – Ian

+0

@它是固定的。 – alfasin

+0

沒問題。那麼現在你可能想顯示循環而不是硬編碼'[0]'(即使你有「等等」) – Ian

相關問題