2013-04-22 70 views
0

我創建了一個下拉列表並獲取了數組中的選項標記值。我想檢查文本框的值是否與數組值相匹配。檢查數組中的特定值

HTML:

<select> 
<option>test1</option> 
<option>test2</option> 
<option>test3</option> 
<option>test4</option> 
</select> 
<input type="text" id="txt" /> //textbox 
<input class="bt" type="button" id="btntest" value="Check for the Value"> 

我使用以下的Jquery得到陣列

var values = $('select').children('option').map(function (i, e) 
{ 
return e.innerText; 
}); 

現在變量保存該結果作爲TEST1,TEST2,TEST3,TEST4

問題:如果用戶鍵入「test2「in textbox(txt),如何檢查test2在數組中是否可用等等。如果用戶輸入除數組值之外的任何內容,則應顯示錯誤消息。

請找到fiddle

回答

0

Fiddle

$('#btntest').click(function() { 
    if ($.inArray($('#txt').val(), values) > -1) { 
     console.log("available"); 
    }else{ 
    console.log("not available"); 
    } 
}); 
+0

感謝小提琴阿迪爾 – user2218497 2013-04-22 11:31:44

+0

當我選擇從列表中它的第一項說「不可用」 – user2218497 2013-04-22 11:33:54

+0

確保你有'> -1'在條件 – 2013-04-22 11:37:15

1

您可以使用jQuery InArray

jQuery.inArray($('#txt').val() , values) 
0

據我瞭解,你需要程序自動選擇該選項,這樣它更容易

var value = $('#txt').val(); 
$('option', 'select').filter(function(){return this.innerText == value;}).prop("selected", true)