【问题标题】:How do I enable/disable options in Select Box using jquery如何使用 jquery 在选择框中启用/禁用选项
【发布时间】:2012-06-12 19:01:52
【问题描述】:

我有一个选择框,其中包含使用 php 动态生成的选项和 optgroup。现在,当我选择“全部”所有其他 optgroup 时,选项应该被禁用,当我选择“以外的任何选项时” ALL”应该禁用“ALL”选项

<select name="select1" id ="select1" onchange="handleSelect()">
    <option value ="-1">ALL</option>
    <optgroup label="CARS">
        <option value="ford">FORD</option>
        <option value="Nissan">Nissan</option>
    </optgroup>
</select>
<script>
    function handleSelect() {
        var selectVal = $("#select1:selected").text();
        if (selectVal == "ALL") {
            // cannot disable all the options in select box
            $("#select1  option").attr("disabled", "disabled");
        }
        else {
            $("#select1 option[value='-1']").attr('disabled', 'disabled');
            $("#select1 option").attr('disabled', '');
        }
    }
</script>

我怎样才能使它工作?

【问题讨论】:

  • 如果在您选择“全部”时所有选项都被禁用(反之亦然),您如何选择除“全部”以外的任何选项

标签: jquery-ui jquery jquery-selectors


【解决方案1】:

这有点奇怪,但这里的代码可以满足您的要求。

$('select').on('change', function() {
    if (this.value == '-1') {
        $('optgroup option').prop('disabled', true);
    } else {
        $('optgroup option').prop('disabled', false);
    }
});

现场示例 - http://jsfiddle.net/NpNFh/

【讨论】:

    【解决方案2】:

    您可以使用以下代码。假设您有如下三个选择框

    <select class="sel_box" id="sel_1" onchange="disable_sel(this.value);" ></select>
    <select class="sel_box" id="sel_2" onchange="disable_sel(this.value);" ></select>
    <select class="sel_box" id="sel_3" onchange="disable_sel(this.value);" ></select>
    

    在函数中让'opt'作为参数现在使用以下

    $('.sel_box option[value="'+opt+'"]').attr("disabled", true);
    

    【讨论】:

      【解决方案3】:

      您可以对 disabled 属性的语法使用两种变体,具体取决于您所针对的 HTML 版本:

      HTML4: <option value="spider" disabled>Spider</option>
      XHTML: <option value="spider" disabled="disabled">Spider</option>
      

      【讨论】:

        猜你喜欢
        • 2012-07-22
        • 1970-01-01
        • 2013-11-17
        • 2019-09-23
        • 1970-01-01
        • 2012-08-29
        • 2011-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多