简体   繁体   中英

Disable options on select2 after specific one is selected

I am using a select2 in my web site with 10 options let's say. So I have this js:

$("#myselect").select2({ 
    maximumSelectionLength: 3
});

When the option 1 is selected I want to disable all the other options on the Select2. Somehow like skip the maximumSelectionLength and suddenly allow only one to be selected. But this should happen only if I select the option 1.

If I choose the option 2 for example I just need to deactivate the option 1.

So in general the option 1 needs to be excluded from the max of 3 selection if something else is selected, and should deactivate all the other options in case it is selected in the beginning. I hope I make it quite clear in the description.

Is something like this possible and how?

I tried this one>

if($("#myselect").val() == 1){
    $("#myselect").find("option").each(function(){
        if($(this).val() != 1){
            $(this).attr("disabled", "disabled");
        }
    });
}

and this actually adds the disabled attribute to all the option when the option 1 is selected, but not on the produced select2 html code, only on my initial html, so it does not actually work.

Thanks in advance

Well after @karan3112 recommendation I added this one

   $("#myselect").select2({maximumSelectionLength:3}).trigger('selection:update'); 

after adding the disabled attributed and works just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM