2014-12-02 347 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 
    } 
});