jQuery 多选选项 - 检查是否选择了某个选项

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

本文关键字:选项 选择 是否 检查 jQuery      更新时间:2023-09-26

我有一个 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>

我正在尝试做的是检查是否在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>

但它不起作用。

谁能帮我?

提前感谢您的帮助。

请按照以下代码进行操作

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

您可以在下面检查小提琴

多选

您可以使用

:selected选项选择器来确定它是否已被选中

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

据我所知,当您更改<select>框中的选项时,您正在尝试检测是否已选择它,对吗?

试试这个:

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