2014-12-02 205 views
6

我有一個HTML多選擇框jQuery的多項選擇選項 - 檢查是否選擇一個選項或不

<form action="form_action.php" method="Post"> 
<select name="cars[]" multiple id="select_id"> 
    <option value="all" id="option_id">All</option> 
    <option value="volvo">Volvo</option> 
    <option value="saab">Saab</option> 
    <option value="opel">Opel</option> 
    <option value="audi">Audi</option> 
</select> 
<input type="submit"> 
</form> 

我所試圖做的是檢查,如果選擇「全部」是jQuery的選擇與否。

我已經試過是

<script> 
     $(document).ready(function() 
     { 
      $('#option_id') 
       .click(
        function() 
        { 
         if ($("#select_id option[value='all']").length == 0) { //value does not exist so add 
          //Do something if not selected 
         } 
         else 
         { 
          //DO something if selected 
         } 
         //$("#select_id option:selected").removeAttr("selected");   //Remove 
         //$("#select_id option").attr('selected', 'selected');  //Add 
        } 
       ); 
     }); 
    </script> 

但它無法正常工作。

任何人都可以幫助我嗎?

在此先感謝您的幫助。

回答

12

請做如下代碼

$('#option_id').click(function(){ 
if ($("#select_id option[value=all]:selected").length > 0){ 
    alert('all is selected'); 
} 
else{ 
    //DO something if not selected 
} 
//$("#select_id option:selected").removeAttr("selected");   //Remove 
//$("#select_id option").attr('selected', 'selected');  //Add 
}); 

您可以檢查以下小提琴

Multi Select

+0

這種方法不適用於我。 – 2014-12-02 05:22:55

+0

@TheThinker:這是針對上述問題。如果您的問題不同,請爲此發佈單獨的問題?如果你的問題是相同的,那麼讓我知道你在做什麼錯誤? – 2014-12-02 05:34:17

4

可以使用:selected選擇的選項,以確定它是否被選中或不

if ($("#select_id option[value=all]:selected").length > 0){ 
    //all is selected 
} 
+0

它不工作 這是一個多選。 所以,選項是一個數組。 你能告訴我一種不同的方式嗎? – 2014-12-02 04:47:50

1

從我所看到的,你想檢測當你在更改的選項是否已選定<select>框,對吧?

試試這個:

$("#select_id").change(function() { 
    if ($(this).find("option:selected").val() == "all") { 
    // all is selected 
    } else { 
    // all isn't selected 
    } 
});