jquery - Limiting select2 selections even when CTRL is used -
select2 provides option limit selections made user, i.e.:
$('.select2').select2({ maximumselectionlength: 3 });
would allow user select 3 items select2 dropdown.
the issue occurs when user uses ctrl select multiple options - select2 doesn't limit selections made when user selects in fashion.
is there way check selection limit whenever ctrl-selection made? failing can disable ctrl-select functionality? (i couldn't find option in docs..)
see reproduction below. try making more 3 selections first clicking them individually , ctrl-clicking them without closing drop-down.
(function($){ $('.select2').select2({ maximumselectionlength: 3 }); })(jquery);
body{ font-family: sans-serif; } .select2{ width: 100%; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script> <select class="select2" multiple="multiple"> <option value="1">option 1</option> <option value="2">option 2</option> <option value="3">option 3</option> <option value="4">option 4</option> <option value="5">option 5</option> <option value="6">option 6</option> <option value="7">option 7</option> </select>
you can listen select2:selecting
event , prevent event if 3 items selected.
at moment, preventing user selecting fourth value, may choose display warning message if want.
(function($){ $('.select2').select2({ maximumselectionlength: 3 }); $(".select2").on("select2:selecting", function(e) { console.log($(this).val(), e.params.args.data); if($(this).val() && $(this).val().length >= 3) { e.preventdefault(); } }); })(jquery);
body{ font-family: sans-serif; } .select2{ width: 100%; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script> <select class="select2" multiple="multiple"> <option value="1">option 1</option> <option value="2">option 2</option> <option value="3">option 3</option> <option value="4">option 4</option> <option value="5">option 5</option> <option value="6">option 6</option> <option value="7">option 7</option> </select>
Comments
Post a Comment