javascript jQuery Multi Select Option - 检查一个选项是否被选中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27242000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:12:11  来源:igfitidea点击:

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

javascriptjqueryhtmljquery-selectors

提问by Abrar Jahin

I have a HTML Multi select box

我有一个 HTML 多选框

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

提前感谢您的帮助。

回答by AB Vyas

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

多选

回答by Milind Anantwar

You can use :selectedselector for option to determine whether it is selected or not

您可以使用:selected选择器作为选项来确定它是否被选中

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

回答by Lucas

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
  }
});