无法取消选择“选择多个”与选择计数器选项和optgroups
我使用的是从这里无法取消选择“选择多个”与选择计数器选项和optgroups
How do you limit options selected in a html select box?
接受答案的代码在“选择多个”菜单来算选定的选项:
var last_valid_selection = null;
$("#select_options").change(function(event) {
if ($(this).val().length > 10) {
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
$("#select_options_text").text("Please select at least one, and up to ten options. You have currently selected "+$(this).val().length);
}
});
该菜单分为六个optgroups。当我点击10个选择时,我无法再按预期做出选择。但是我也不能再使用CTRL +点击选定的选项来取消选择。
如果我删除所有optgroup,菜单功能正常。它也可以正确使用一个和两个optgroups。它似乎只是在添加第三个optgroup时出现上述问题。
我已经在Chrome和Firefox中测试过,并且两者都出现问题。
问题
您有重复的选项,所以当尝试通过调用$(this).val(last_valid_selection)
恢复最后的选择,你可以选择比你真正想要的(即你最终选择超过10个)以上的值。
例如,你有一个以上的Biochemistry
,所以当last_valid_selection
包含Biochemistry
一个实例,所有重复Biochemistry
选项将被选中。
解决方案
使用记住最后一次的有效选择不同的方式。
在这里,我提出了一个使用数据属性的解决方案,并单独存储是否先前选择了一个选项。
function save_selected(select){
$(select).find("option").each(function(){
var t = $(this);
t.data("last-selected", t.is(":selected"));
});
};
function load_selected(select){
$(select).find("option").each(function(){
var t = $(this);
t.attr("selected", t.data("last-selected"));
});
};
$("#select_options").change(function(event) {
if ($(this).val().length > 10) {
load_selected(this);
} else {
save_selected(this);
}
});
使用此方法,每个单独的选项元素都有自己的“上次选择”状态,存储在其自己的数据属性中。不会有重复的冲突。
非常感谢,这很好。 –
您可以添加HTML,甚至更好,reproduca,在上一个的jsfiddle jsfiddl –
重现问题,作为工作在这里预期:http://jsfiddle.net/z9r26r3j/1/ –
这里的一个jsFiddle使用实际的选择菜单选项:https://jsfiddle.net/gzdrL5wu/2/ –