12

我有一个包含选项的选择框,optgroup它是使用 php 动态生成的。现在,当我选择“ALL”所有其他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>

我怎样才能使它工作?

4

3 回答 3

21

这是一种奇怪的事情,但这里的代码可以满足您的要求。

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

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

于 2012-06-08T19:08:25.780 回答
8

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

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

并且在函数中让“选择”是参数现在使用以下

$('.sel_box option[value="'+opt+'"]').attr("disabled", true);
于 2013-06-24T05:26:17.073 回答
0

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

HTML4: <option value="spider" disabled>Spider</option>
XHTML: <option value="spider" disabled="disabled">Spider</option>
于 2012-06-08T17:51:17.670 回答