【问题标题】:jQuery Multi Select Option - Check if a option is selected or notjQuery Multi Select Option - 检查是否选择了一个选项
【发布时间】:2015-01-30 06:16:48
【问题描述】:

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

但它不起作用。

谁能帮帮我?

提前感谢您的帮助。

【问题讨论】:

    标签: javascript jquery html jquery-selectors


    【解决方案1】:

    请按照以下代码进行操作

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

    【讨论】:

    • @TheThinker:这适用于上述问题。如果您的问题不同,请为此发布您的单独问题?如果您的问题相同,请告诉我您遇到了什么错误?
    【解决方案2】:

    据我所知,当您更改&lt;select&gt; 框中的选项时,您正试图检测它是否已被选中,对吧?

    试试这个:

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

    【讨论】:

      【解决方案3】:

      你可以使用:selected选择器来判断是否被选中

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 2019-07-31
        • 2012-12-29
        • 2014-03-28
        • 2017-06-11
        • 1970-01-01
        相关资源
        最近更新 更多