Search code examples
jqueryjquery-selectorshtml-select

How to disable select based on other selected option?


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


Solution

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