Select2 limit number of tags

北城余情 提交于 2019-12-03 04:19:32

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

        });
Aruna Warnasooriya
$("#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.

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.

This is working for me.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!