How to let jquery select2 disable one parameter dynamically?

I have multi-selection and I use jquery select2.I want to disable one parameter in another multi-select when this parameter is selected in one multi-select. I am writing this code, but it works.

$("select.multiselect").on("change", function(e) {
    if(e.added){
        for(var i=0;i<this.options.length;i++){
            var vals = $(this).select2("val");
            for(var j=0;j<vals.length;j++){
                if(this.options[i].value===vals[j]){
                    this.options[i].selected=true;
                }
            }
        };
    }

    if(e.removed){
        for(var i=0;i<this.options.length;i++){
            if(this.options[i].value===e.removed.id){
                this.options[i].selected=false;
            }
        };
    }
});

how to do it?

+3
source share
1 answer

It was harder than I thought, but here is what I came up with:

$('select.multiselect').on('change', function(e) {

    // the selected values
    var vals = $(this).select2("val");

    // selects contains all the OTHER select forms
    var selects = $('select').not('#'+$(this).attr('id'));

    // loop trough all the selects
    for (var i = 0; i < selects.length; i++) {
        //re-enable all options before
        $(selects[i]).find('option').removeAttr('disabled');
        // loop trough all the values
        for (var j = 0; j < vals.length; j++) {
            // disabled attribute
            $(selects[i]).find('option[value='+vals[j]+']').attr('disabled', 'disabled');
        }
    }
});

Here is the fiddle if you want to see the result in action

Make sure all your items selectare unique id.

+4
source