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


i'm using code accepted answer here

how limit options selected in html select box?

to count selected options in 'select multiple' menu:

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 @ least one, , ten options. have selected "+$(this).val().length);      }      }); 

the menu divided 6 optgroups. when hit 10 selections can no longer make selections, expected. i can no longer use ctrl+click on selected options deselect them.

if remove optgroups, menu functions correctly. functions correctly 1 , 2 optgroups. seems when third optgroup added problem described above appears.

i have tested in chrome , firefox , problem occurs in both.

problem

you have duplicate options, when try restore last selection calling $(this).val(last_valid_selection), selecting more 1 value want (i.e. end selecting more 10).

for example, have more 1 biochemistry, when last_valid_selection contains 1 instance of biochemistry, all duplicate biochemistry options selected.

solution

use different way of remembering last valid selections.

here present solution using data attribute , individually store whether or not option has been selected.

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

using method, each individual option element has own "last selected" state stored in own data attribute. there no duplicate conflicts.

demo: https://jsfiddle.net/alan0xd7/gzdrl5wu/12/


Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -