imperium2335
imperium2335

Reputation: 24132

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.

Upvotes: 52

Views: 89891

Answers (7)

Charlie
Charlie

Reputation: 3374

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

 });

Upvotes: 5

Tayyeb
Tayyeb

Reputation: 147

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

Upvotes: 0

Sarath Ak
Sarath Ak

Reputation: 8699

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

Upvotes: 12

Viral M
Viral M

Reputation: 261

This is working for me.

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

Upvotes: 0

Aruna Warnasooriya
Aruna Warnasooriya

Reputation: 339

$("#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.

Upvotes: 3

Magnus Engdal
Magnus Engdal

Reputation: 5634

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!

Upvotes: 99

Mr Br
Mr Br

Reputation: 3901

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.

Upvotes: 1

Related Questions