Select2 limit number of tags
$("#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.
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
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
});
});