jQuery - 禁用/启用下拉选项

16

我需要一些关于 jQuery if 条件的帮助。 我已经搜索和测试了几个小时了,任何帮助都将不胜感激!!! 我得到了这段 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>

并且这个 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');

    });
}

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

问题是:

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

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

2个回答

25

试试这个:

$(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);
        }
    });
});

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


3
不要使用live,它已被弃用。 - Vins

0
对于那些使用Select2 4.0.13的人来说,你可以通过以下方式禁用单个选项:
$('#categories').select2({
   disabled: false
});

对于使用 Select2 4.0.13 的用户,您可以使用以下方法禁用整个下拉列表:

$('select').select2({
   disabled: false
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接