如何使用 jquery 在选择框中启用/禁用选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10953589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:01:13  来源:igfitidea点击:

How do I enable/disable options in Select Box using jquery

jquery-uijqueryjquery-selectors

提问by Someone

I have a select box which contains the options and optgroupthat are generated dynamically using php.Now when I select "ALL" all the other optgroup, options should be disabled and when I select any option other than "ALL" the "ALL" option should be disabled

我有一个选择框,其中包含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>

How can I make this working?

我怎样才能使这个工作?

回答by TJ VanToll

This is kind of a strange thing to be doing but here's code that meets your requirements.

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

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

Live Example- http://jsfiddle.net/NpNFh/

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

回答by Someone

You can use the following code.Let us consider you have three select boxes as follows

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

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

and in function let 'opt' is argument now use following

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

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

回答by Gaurav

You can use two variations on the syntax for the disabled attribute, depending on the version of HTML you are targeting:

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

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