Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set limit in selection for sumo dropdown

I have used this jquery plugin SumoSelect for drop-down select with check-box

<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 working fine with check-bow selections. But I want to put some limitation for different users with this selection.

I have tried below jquery code but it not working proper

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();
    }
  });  });
like image 243
Nikunj Chavda Avatar asked Oct 13 '15 09:10

Nikunj Chavda


Video Answer


1 Answers

You can use sumo methods unSelectAll and selectItem and the triggerChangeCombined option on the plugin init.

Ref: http://hemantnegi.github.io/jquery.sumoselect/

In the change event if the limit is raised 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/

like image 51
Irvin Dominin Avatar answered Sep 18 '22 13:09

Irvin Dominin