To limit number of tags with jQuery Select2 drop down, we can set the maximumSelectionLength
property to the max number of values we can select.
For instance, we can write:
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="select2" multiple>
<option>Foo</option>
<option>Bar</option>
<option>Baz</option>
<option>Some Text</option>
<option>Other Text</option>
</select>
We create a select element with the multiple
attribute.
Then we write:
$('select').select2({
maximumSelectionLength: 3
});
We call select2
with an object with the maximumSelectionLength
property set to 3.
Now we can only select 3 choices max.