简体   繁体   English

jQuery Multi Select Option-检查是否选择了一个选项

[英]jQuery Multi Select Option - Check if a option is selected or not

I have a HTML Multi select box 我有一个HTML Multi选择框

<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>

What I am trying to do is check if option "All" is selected or not in jQuery. 我想做的是检查是否在jQuery中选择了“全部”选项。

What I have tried is 我试过的是

<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>

But it is not working. 但这是行不通的。

Can anyone help me please? 谁能帮我吗?

Thanks in advance for helping. 在此先感谢您的帮助。

Please do as below code 请执行以下代码

$('#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
});

You can check below fiddle 您可以在下面查看小提琴

Multi Select 多选

You can use :selected selector for option to determine whether it is selected or not 您可以使用:selected选择器作为选项来确定是否选择它

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

From what I can see, you're trying to detect whether it has been selected when you change the option in the <select> box, right? 据我所知,您正在尝试检测在更改<select>框中的选项时是否已选择它,对吗?

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM