4

I have some multiselect and i use jquery select2.I want to disable one option in other multiselect when this option is selected in one multiselect. i write this code,but it does work.

$("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?

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
user2219372
  • 2,385
  • 5
  • 23
  • 26

1 Answers1

7

It was more complicated then 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's a fiddle if you want to see the result in action

Make sure all your select elements have a unique id.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Skwal
  • 2,160
  • 2
  • 20
  • 30
  • 9
    it seems that on the latest version you have to call $( object ).select2() again after updating the options? – kroe Jul 07 '15 at 16:17