How to disable select based on other selected opti

2019-08-06 12:53发布

I have a problem with jQuery function. I want based on one selected option to disable other select. In my case, I want to disable select2 if option 1 from select 1 is chosen. So i use this jQuery function:

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

But this works only if I first select option 2(or any other option form this select) and then reselect option 1(i suppose that is because use of change function). How to disable select2 when by the default select1 is set to option 1???

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

This also wont work :/

2条回答
放荡不羁爱自由
2楼-- · 2019-08-06 13:31

Almost same code.

$(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');
 } }
查看更多
Luminary・发光体
3楼-- · 2019-08-06 13:38

It sounds like you want to trigger a 'change' event at startup.

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

So,

$(document).ready(function(e) {
    $('.select1').change(function(e) {
        if ($('.select1').val()==1){
            $('.select2').attr('disabled','disabled');
        }
        else{
            $('.select2').removeAttr('disabled');
        }
    });
    $('.select1').trigger('change');
});
查看更多
登录 后发表回答