2015-07-13 278 views
2

我使用的是從這裏無法取消選擇「選擇多個」與選擇計數器選項和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中測試過,並且兩者都出現問題。

+0

您可以添加HTML,甚至更好,reproduca,在上一個的jsfiddle jsfiddl –

+0

重現問題,作爲工作在這裏預期:http://jsfiddle.net/z9r26r3j/1/ –

+0

這裏的一個jsFiddle使用實際的選擇菜單選項:https://jsfiddle.net/gzdrL5wu/2/ –

回答

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/

+0

非常感謝,這很好。 –

相關問題