6

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();
    }
  });  });
Nimeshka Srimal
  • 8,012
  • 5
  • 42
  • 57
Nikunj Chavda
  • 433
  • 3
  • 15

2 Answers2

5

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/

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
  • It working but when call "$this[0].sumo.unSelectAll();" also log error " Cannot read property 'length' of null" for me. Cant find where yet. I think it in sumo.js – Murat Özbayraktar Jul 18 '19 at 06:55
0

There is better sample.

Dont forgot 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();
        }
    });