jQuery - 禁用/启用选择选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11629669/
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:47:31  来源:igfitidea点击:

jQuery - disable/enable select options

jqueryoption

提问by Adrian

I need some help with jquery if condition. I've been searching and testing for hours, any help would be great !!! I get this HTML code:

如果条件允许,我需要一些有关 jquery 的帮助。我已经搜索和测试了几个小时,任何帮助都会很棒!!!我得到这个 HTML 代码:

<label id="label1" for="date_from">Value:</label>
<input value="" />

<select id="select1" name="select1">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>

<select id="select2" name="select2">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>

and this jquery function:

和这个 jquery 函数:

if ( $('#label1').val() < 3 ) {
           $('select').change(function() {

            $('#select1, #select2').not(this)
                .children('option[value=' + this.value + ']')
                attr('disabled', true)
                .siblings().removeAttr('disabled');

        });
}
else {
    $('select').change(function() {

        $('#select1, #select2').not(this)
            .children('option[value=' + this.value + ']')
            .attr('disabled', false)
            .siblings().removeAttr('disabled');

    });
}

I'm a beginner in jquery, and I don't know is this code is written correctly because it doesn't work.

我是 jquery 的初学者,我不知道这段代码是否正确编写,因为它不起作用。

The problem is:

问题是:

When the input value is less then 3 then select option in select2 is the same as in select1 and the rest of options in select2 are disable. When the input value is greater then 3 then options in select1 and select2 are enable.

当输入值小于 3 时,select2 中的 select 选项与 select1 中的相同,并且 select2 中的其余选项被禁用。当输入值大于 3 时,将启用 select1 和 select2 中的选项。

Best Regards, Thank you for reading this jquery newbie post...

最好的问候,感谢您阅读这篇 jquery 新手帖子......

回答by artwl

try this:

尝试这个:

$(function(){
    $("input").change(function(){
        if ( $(this).val() < 3 ) {
            $('#select2').prop('disabled', true);
            $('#select1').on("change",function() {
                $('#select2').val($(this).val());
            });
        }else {
            $("#select1").off();
            $('#select1, #select2').prop('disabled', false);
        }
    });
});

Demo:http://jsfiddle.net/qhPp7/2/

演示:http: //jsfiddle.net/qhPp7/2/