如何让jquery select2动态地禁用一个选项? [英] how to let jquery select2 disable one option dynamically?
本文介绍了如何让jquery select2动态地禁用一个选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些多选,我使用jquery select2.I想要在一个多选中选择此选项时禁用其他多选中的一个选项。
i写这段代码,但它确实有用。
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;
}
};
}
});
该怎么做?
推荐答案
这比我想的要复杂,但这是我想出的:
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
确保所有选择
元素具有唯一的 id
。
Make sure all your select
elements have a unique id
.
这篇关于如何让jquery select2动态地禁用一个选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文