Set a limit in the selection for a sumo

I used this jquery SumoSelect plugin to select using checkbox

<select multiple="multiple" class="SlectBox" name="cat_ids[]"> <option value="op1">Options1</option> <option value="op2">Options2</option> <option value="op3">Options3</option> <option value="op4">Options4</option> <option value="op5">Options5</option> </select> 

This drop-down list works great with a checkmark option. But I want to put some restrictions for different users with this choice.

I tried below jQuery code but it does not work properly

 jQuery(document).ready(function($){ var last_valid_selection = null; $('.SlectBox').change(function(event) { if ($(this).val().length > 2) { alert('You can only choose 2!'); $(this).val(last_valid_selection); } else { last_valid_selection = $(this).val(); } }); }); 
+6
source share
2 answers

You can use the unSelectAll and selectItem as well as the triggerChangeCombined parameter in the triggerChangeCombined init.

Link: http://hemantnegi.imtqy.com/jquery.sumoselect/

In the event of a change, if the limit is increased, you can deselect all and set the last valid selection by the index of each element.

Code:

 $('#island').SumoSelect({ triggerChangeCombined: true, placeholder: "TestPlaceholder" }); var last_valid_selection = null; $('#island').change(function (event) { if ($(this).val().length > 2) { alert('You can only choose 2!'); var $this = $(this); $this[0].sumo.unSelectAll(); $.each(last_valid_selection, function (i, e) { $this[0].sumo.selectItem($this.find('option[value="' + e + '"]').index()); }); } else { last_valid_selection = $(this).val(); } }); 

Demo: http://jsfiddle.net/IrvinDominin/80xLm01g/

+5
source

There is a better sample.

Did not forget triggerChangeCombined: true

  var last_selection = null; var load_selection = false; $('#SeasonIdList').change(function (event) { if (load_selection == true) { return false; } if ($(this).val() != null && $(this).val().length > 3) { load_selection = true; var $this = $(this); $this[0].sumo.unSelectAll(); $.each(last_selection, function (i, e) { $this[0].sumo.selectItem($this.find('option[value="' + e + '"]').index()); }); load_selection = false; } else { last_selection = $(this).val(); } }); 
0
source

Source: https://habr.com/ru/post/1233595/


All Articles