如何使用jquery在Select Box中启用/禁用选项

Som*_*one 12 jquery jquery-ui jquery-selectors

我有一个选择框,其中包含选项,并optgroup使用php.Now动态生成当我选择"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>
Run Code Online (Sandbox Code Playgroud)

我怎样才能使这个工作?

TJ *_*oll 21

这是一件奇怪的事情,但这里的代码符合您的要求.

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

实例 - http://jsfiddle.net/NpNFh/


小智 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>
Run Code Online (Sandbox Code Playgroud)

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

$('.sel_box option[value="'+opt+'"]').attr("disabled", true);
Run Code Online (Sandbox Code Playgroud)