繁体   English   中英

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

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

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

我想做的是检查是否在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
  }
});

暂无
暂无

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

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