Search code examples
javascriptjquerytagsjquery-select2

Select2 limit number of tags


Is there a way to limit the number of tags a user can add to an input field using Select2?

I have:

$('#tags').select2({
    containerCssClass: 'supplierTags',
    placeholder: "Usual suppliers...",
    minimumInputLength: 2,
    multiple: true,
    tokenSeparators: [",", " "],
    placeholder: 'Usual suppliers...',
            createSearchChoice: function(term, data) {
                if ($(data).filter(function() {
                    return this.name.localeCompare(term) === 0;
                }).length === 0) {
                    return {id: 0, name: term};
                }

            },
    id: function(e) {
        return e.id + ":" + e.name;
    },
    ajax: {
        url: ROOT + 'Call',
        dataType: 'json',
        type: 'POST',
        data: function(term, page) {
            return {
                call: 'Helpers->tagsHelper',
                q: term
            };
        },
        results: function(data, page) {
            return {
                results: data.tags
            };
        }
    },
    formatResult: formatResult,
    formatSelection: formatSelection,
    initSelection: function(element, callback) {
        var data = [];
        $(element.val().split(",")).each(function(i) {
            var item = this.split(':');
            data.push({
                id: item[0],
                name: item[1]
            });
        });
        callback(data);
    }
});

It would be great if there could be/is a simple parameter like limit: 5 and a callback to fire when the limit is reached.


Solution

  • 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!