我在这里使用接受的答案中的代码
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);
}
});
菜单分为六个选项组。当我点击 10 个选项时,我无法再像预期的那样进行选择。但是我也不能再使用 CTRL + 单击选定的选项来取消选择它们。
如果我删除所有 optgroups,菜单功能正常。它也可以与一个和两个 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);
}
});
使用此方法,每个单独的选项元素都有自己的“最后选择”状态,存储在自己的数据属性中。不会有重复的冲突。
关于javascript - 无法使用选择计数器和 optgroups 取消选择 'select multiple' 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31382283/