javascript 如何让 jquery select2 动态禁用一个选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21909391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to let jquery select2 disable one option dynamically?
提问by user2219372
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.
我有一些多选,我使用 jquery select2。当在一个多选中选择此选项时,我想禁用其他多选中的一个选项。我写了这段代码,但它确实有效。
$("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?
怎么做?
回答by Skwal
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 fiddleif you want to see the result in action
如果你想看到结果,这是一个小提琴
Make sure all your select
elements have a unique id
.
确保您的所有select
元素都具有唯一的id
.