无法取消选择多个'选择计数器和optgroups的选项

时间:2015-07-13 11:34:12

标签: javascript jquery select optgroup

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

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 +点击选定的选项来取消选择

如果我删除所有选项组,菜单功能正常。它还可以正常运行一个和两个optgroup。它似乎只是在添加第三个optgroup时出现上述问题。

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

1 个答案:

答案 0 :(得分:1)

<强>问题

您有重复的选项,因此当尝试通过调用$(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);
    }
});

使用此方法,每个单独的选项元素都有自己的&#34;最后选择&#34;状态存储在自己的数据属性中。没有重复的冲突。

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

相关问题