How to disable select based on other selected option?

烈酒焚心 提交于 2020-01-05 08:59:18

问题


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


来源:https://stackoverflow.com/questions/15888444/how-to-disable-select-based-on-other-selected-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!