Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  106] [ 6]  / answers: 1 / hits: 80931  / 11 Years ago, mon, january 27, 2014, 12:00:00

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.


More From » jquery

 Answers
12

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!


[#72921] Saturday, January 25, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
kevonmoisesf questions
Sat, Jan 23, 21, 00:00, 3 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
Wed, Jun 12, 19, 00:00, 5 Years ago
;