How to disable select based on other selected opti

2019-08-06 13:31发布

问题:

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

回答1:

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');
});


回答2:

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');
 } }