【问题标题】:Unable to deselect 'select multiple' options with selection counter and optgroups无法使用选择计数器和 optgroup 取消选择“选择多个”选项
【发布时间】:2015-07-13 11:34:12
【问题描述】:

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

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); 
    }     
});

菜单分为六个 optgroup。当我点击 10 个选项时,我无法再按预期进行选择。但是我也不能再使用 CTRL+单击选定的选项来取消选择它们。

如果我删除所有 optgroup,菜单将正常运行。它还可以与一个和两个 optgroup 一起正常工作。似乎只有在添加第三个 optgroup 时才会出现上述问题。

我在 Chrome 和 Firefox 中进行了测试,两者都出现了问题。

【问题讨论】:

  • 你能在 jsfiddl 中添加你的 HTML,甚至更好地重现它
  • 在 jsFiddle 上重现问题,在此处按预期工作:jsfiddle.net/z9r26r3j/1
  • 这是一个使用实际选择菜单选项的 jsFiddle:jsfiddle.net/gzdrL5wu/2

标签: javascript jquery select optgroup


【解决方案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);
    }
});

使用这种方法,每个单独的选项元素都有自己的“最后选择”状态存储在自己的数据属性中。不会有重复的冲突。

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

【讨论】:

    猜你喜欢
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多