如何根据其他选择的选项禁用选择?

时间:2013-04-08 20:32:58

标签: jquery jquery-selectors option

我的jQuery函数有问题。我希望基于一个选定的选项来禁用其他选择。在我的情况下,如果选择了选项1中的选项1,我想禁用select2。所以我使用这个jQuery函数:

$(document).ready(function(e) {
$('.select1').change(function(e) {
    if ($('.select1').val()==1){
        $('.select2').attr('disabled','disabled');
    }
    else{
        $('.select2').removeAttr('disabled');
    }
})
});

但这只有在我首先选择选项2(或此选择的任何其他选项)然后重新选择选项1(我想这是因为使用更改功能)时才有效。如何在默认情况下将select1设置为选项1 ???

时禁用select2
$(document).ready(function(e) {
    if ($('.select1').val()==1){
    $('.select2').attr('disabled','disabled');
}
else{
    $('.select2').removeAttr('disabled');
}
})

这也不会起作用:/

2 个答案:

答案 0 :(得分:5)

听起来你想在启动时触发'更改'事件。

$('.select1').trigger('change');

所以,

$(document).ready(function(e) {
    $('.select1').change(function(e) {
        if ($('.select1').val()==1){
            $('.select2').attr('disabled','disabled');
        }
        else{
            $('.select2').removeAttr('disabled');
        }
    });
    $('.select1').trigger('change');
});

答案 1 :(得分:1)

几乎相同的代码。

$(document).ready(function(e) {
 change('.select1');
 $('.select1').change(function(e) {
   change(this);
 }) });  function change(sel){
if ($(sel).val()==1){
    $('.select2').attr('disabled','disabled');
  }
  else{
    $('.select2').removeAttr('disabled');
 } }
相关问题