无法使用选择计数器和选项组取消选择 'select multiple' 个选项

Unable to deselect 'select multiple' options with selection counter and optgroups

我在此处使用已接受答案中的代码

How do you limit options selected in a html select box?

计算 'select multiple' 菜单中的选定选项:

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 一起正常运行。似乎只有在添加第三个 optgroup 时才会出现上述问题。

我已经在 Chrome 和 Firefox 中进行了测试,但两者都存在问题。

问题

您有重复的选项,因此当尝试通过调用 $(this).val(last_valid_selection) 恢复上次选择时,您可能选择了比您实际需要的多于一个的值(即您最终选择了 10 个以上)。

例如,您有多个 Biochemistry,因此当 last_valid_selection 包含一个 Biochemistry 实例时,all 重复 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);
    }
});

使用此方法,每个单独的选项元素都有自己的 "last selected" 状态,存储在自己的数据属性中。不会有重复的冲突。

演示:https://jsfiddle.net/alan0xd7/gzdrL5wu/12/