Select2 limit number of tags
Asked Answered
S

7

51

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.

Schoonover answered 27/1, 2014 at 11:43 Comment(0)
D
97

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!

Douglass answered 27/1, 2014 at 11:50 Comment(6)
Thanks! Is there a way to fire an even when this limit is reached? That would be perfect.Schoonover
There is no native callback, but I added a possible solution to my answer.Douglass
Note that maximumSelectionSize has been replaced with maximumSelectionLength.Pigfish
how to use this in Yii2?Timework
Noted in the release notes, the formatters were moved to the language option. (maximumSelected).Mccreary
this still does not work when using 'tokenSeparators' => [',', ' '],it allows to select more than the limitHong
S
12

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

Swordfish answered 24/10, 2019 at 5:47 Comment(0)
T
5

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
      });

 });
Trismus answered 2/12, 2016 at 14:59 Comment(0)
Z
3
$("#keywords").select2({
    tags : true,
    width :'100%',
    tokenSeparators: [','],
    maximumSelectionLength: 5,
    matcher : function(term,res){
        return false;
    },
    "language": {
        'noResults': function(){
            return "Type keywords separated by commas";
        }
    }
}).on("change",function(e){
    if($(this).val().length>5){
        $(this).val($(this).val().slice(0,5));
    }
});

Try like this. It'll short up to 5 keywords.

Zyrian answered 6/12, 2016 at 11:51 Comment(0)
H
1

This is not working for me, I am getting query function not defined for Select2, so here is another workaround.

        var onlyOne=false;
         $("selector").select2({
            maximumSelectionSize:function(){
                if(onlyOne==true)
                    return 1;
                else
                    return 5;
            }
         });

This setting can be defined as function and it's called every time you start searching something.

Important thing is that you have something defined outside this select2 closure so you can check it (access it). In this case you could somewhere in your program change value of onlyOne and of course this returned limit can also be dynamical.

Hoarhound answered 1/7, 2014 at 19:21 Comment(1)
maximumSelectionSize can now be set as an integer to limit the number of selections.Stickle
A
0

This is working for me.

 $("#category_ids").select2({ maximumSelectionLength: 3 });
Andee answered 30/5, 2018 at 10:48 Comment(0)
U
0

Send the Get Request to action method and the Map the class properties to drop down id and text property

$("#DropDownId").select2({
       minimumInputLength: 3,
       maximumSelectionLength: 10,
    tags: [],
    ajax: {
        url: "@Url.Action("ActionName", "ControllerName")",
        type: "get",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                Title: params.term // search term
            };
        },
        processResults: function (response) {
            return {
                results: $.map(response, function (item) {
                    return {
                        text: item.Title,
                        id: item.Id
                    }
                })
            };
        }
    }
});

Action Method


 [HttpGet]
        public JsonResult ActionName(string Title)
        {
            ClassName obj= new ClassName ();
            obj.Title = "PMPAK";
            obj.Id= -1;
            obj.Add(nibafInstitute);

            return Json(obj, JsonRequestBehavior.AllowGet);
        }
     public class ClassName 
    {
        public int Id{ get; set; }

        public string Title { get; set; }
    }
Ultranationalism answered 7/7, 2021 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.