2010-10-07 30 views

回答

2

你可以用jQuery做

使用Attribute Equals Selector

看到

Check if value is in select list with JQuery

在JavaScript中,你可以像

運行
for (var i=0; i<document.getElementById('mySelect').options.length; i++) 
      { 
      if (document.getElementById('mySelect').options[i].text == seachtext) 
      { 
      alert('found'); 
      break; 
      } 
     } 
+2

不要以爲OP正在尋找一個jQuery的解決方案... – chigley 2010-10-07 06:33:36

+0

我也是用某種加入和Option.prototype打遺憾。進入更多的問題比我預期:) – mplungjan 2010-10-07 06:38:53

+0

我只是重讀這個問題,雖然它當然可以用純JavaScript,但我一定會使用jQuery方法,否則它會變得雜亂! – chigley 2010-10-07 06:51:44

7

您無法擴展元素select -element所具有的方法。因此,如果沒有額外的函數來檢查select中是否存在值,將不會有解決方案。

一個「解決方案」沒有環可能是由以下...

function SelectHasValue(select, value) { 
    obj = document.getElementById(select); 

    if (obj !== null) { 
     return (obj.innerHTML.indexOf('value="' + value + '"') > -1); 
    } else { 
     return false; 
    } 
} 
+0

這會比使用循環更有效嗎? – 2010-10-07 08:09:29

+2

不,它不會。看看http://jsbin.com/ewevu3和測試它你自己:) – Andreas 2010-10-07 08:54:21

+0

哎呀..所以我想循環是所有的左邊...生病去與它... – 2010-10-08 06:34:48

1

這個工作對我來說,當從POST參數的頁面負載值,因此,如果值不存在選擇上,提醒用戶;否則,繼續(或警示):

document.getElementById('your_select_id').value = target_value; 
if (document.getElementById('your_select_id').value !== target_value){ 
alert('This value is not in Select'); 
    return; 
} 
1

if(!$('#select-box').find("option:contains('" + thevalue + "')").length){ 
 
//do stuff 
 
}

+2

提問者已經請求了一個JavaScript解決方案,儘管jQuery是一個JavaScript庫,但假設他們正在尋找一個香草JS解決方案似乎是安全的。 – 2017-07-23 23:00:29

0

與ecma6:

let option = document.getElementById('selbox').querySelector('[value="' + my_value + '"]'); 

這將找到包含的屬性值= 「MY_VALUE」 的第一要素。

PS:我的西班牙式英語:)

相關問題