Select2 limit number of tags Select2 limit number of tags javascript javascript

Select2 limit number of tags


Sure, with maximumSelectionLength like so:

$("#tags").select2({    maximumSelectionLength: 3});

Maximum Selection Length

Select2 allows the developer to limit the number of items that can be selected in a multi-select control.

http://ivaynberg.github.io/select2/

It has no native callback, but you can pass a function to formatSelectionTooBig like this:

$(function () {    $("#tags").select2({        maximumSelectionLength: 3,        formatSelectionTooBig: function (limit) {            // Callback            return 'Too many selected items';        }    });});

http://jsfiddle.net/U98V7/

Or you could extend formatSelectionTooBig like this:

$(function () {    $.extend($.fn.select2.defaults, {        formatSelectionTooBig: function (limit) {            // Callback            return 'Too many selected items';        }    });    $("#tags").select2({        maximumSelectionLength: 3    });});

Edit

Replaced maximumSelectionSize with the updated maximumSelectionLength. Thanks @DrewKennedy!


The accepted answer doesn't mention that the maximumSelectionLength statement should be inside the document.ready function. So for anyone who is having the same trouble I did, here is the code that worked for me.

 $(document).ready(function() {          $("#id").select2({            maximumSelectionLength: 3          });        });


method 1

$("#tags").select2({    maximumSelectionLength: 3});

method 2

<select data-maximum-selection-length="3" ></select>

list of all available options https://select2.org/configuration/options-api