select2 provides an option for you to limit the selections that are made by the user, I.E.:
$('.select2').select2({
maximumSelectionLength: 3
});
Would only allow the user to select 3 items from the select2 dropdown.
The issue occurs when the user uses Ctrl to select multiple options - select2 doesn't limit the selections made when the user selects in this fashion.
Is there a way to check the selection limit whenever a CTRL-selection is made? Failing that can I disable the CTRL-select functionality? (I couldn't find an option for this in the docs..)
See my reproduction below. Try making more than 3 selections first by clicking them individually and then by CTRL-clicking them without closing the 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>