2010-03-05 50 views
8

我想查看是否在選擇框中選擇了一個選項,如果沒有,我希望它提醒一個字符串。我指的是這個鏈接(Check if option is selected with jQuery, if not select a default),但它不起作用。如何檢查在使用jQuery的選擇框中是否未選擇任何選項?

這裏是我的代碼:

<select id="language" name="language"> 
    <option value=""></option> 
    <option value="1">One</option> 
    <option value="2">Two</option> 
    <option value="3">Three</option> 
</select> 

if(!$("#language option:selected").length) { 
    alert('no option is selected'); 
} 

我幾乎複製鏈接的答案,但它仍然沒有工作。我錯過了什麼?

回答

15

另一種方式去就是:

if($("#language").attr("selectedIndex") == 0) { 
    alert("You haven't selected anything!"); 
    } 

工作示例在:http://jsbin.com/eluki3/edit

+0

非常感謝! – zeckdude

3
if ($("#language option:selected").val() === "") 
{ 
    alert("No items selected"); 
} 

或者乾脆

if ($("#language").val() === "") 
{ 
    alert("No items selected"); 
} 
+0

需要小心,如果HTML是'

5

也許是因爲第一個被默認選中。

使用

if($('#language :selected').text() == ''){ 
    alert('no option is selected'); 
} 
0

你已經把裏面

$(function() { });

jQuery代碼試試?

DOM準備就緒後需要對它進行評估。

0

我使用解決了同一個問題:

if ($('#mySelector option:selected').get().length>0) { 
    //code 
} else ... 
相關問題