Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  164] [ 1]  / answers: 1 / hits: 24750  / 11 Years ago, thu, february 20, 2014, 12:00:00

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?


More From » jquery

 Answers
31

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.


[#72416] Wednesday, February 19, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 3 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
;