how to modify the tag-it ui plugin https://github.com/aehlke/tag-it (version v2.0) so it only allows selection of x numbers of tags and how to allow only tags that are in the "availableTags-option"?
this question (or the first part of it) is already asked and aswerd in the past but for previous version of the plug-in.
first add custom options (maxTags and onlyAvailableTags) to the plugin file like so...
options: {
itemName : 'item',
fieldName : 'tags',
availableTags : [],
tagSource : null,
removeConfirmation: false,
caseSensitive : true,
maxTags : 9999,//maximum tags allowed default almost unlimited
onlyAvailableTags : false,//boolean, allows tags that are in availableTags or not
allowSpaces: false,
animate: true,
singleField: false,
singleFieldDelimiter: ',',
singleFieldNode: null,
tabIndex: null,
onTagAdded : null,
onTagRemoved: null,
onTagClicked: null
}
next replace the _isNew function with this one...
_isNew: function(value) {
var that = this;
var isNew = true;
var count = 0;
this.tagList.children('.tagit-choice').each(function(i) {
count++;
if (that._formatStr(value) == that._formatStr(that.tagLabel(this))|| count >= that.options.maxTags) {
isNew = false;
return false;
}
if (that.options.onlyAvailableTags && $.inArray(that._formatStr(value),that.options.availableTags)==-1) {
isNew = false;
return false;
}
});
return isNew;
}
Now you can use the options when you initialize tagit. only the sampleTags are allowed with a maximum of 3 tags
$(function(){
var sampleTags = ['php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python'];
//-------------------------------
// Tag events
//-------------------------------
var eventTags = $('#s_tags');
eventTags.tagit({
availableTags: sampleTags,
caseSensitive: false,
onlyAvailableTags: true,
maxTags:3,
})
});
You can just provide this parameter to .tagit:
beforeTagAdded: function(event, ui) {
if($.inArray(ui.tagLabel, availableTags)==-1) return false;
}
where availableTags is your autocomplete array.
Regarding @snuggles query below, I believe (my limited familiarity with the json protocols notwithstanding) you could probably do something like this:
//define autocomplete source
var returnedUsers, jsonUrl = "http://[your server]/user_lookup";
$.getJSON(jsonUrl,function(json){
returnedUsers = json; // or whatever handler you need to use
});
// instantiate tagit
$("#ccList").tagit({
availableTags: returnedUsers,
beforeTagAdded: function(event, ui) {
// only allow existing values
if($.inArray(ui.tagLabel, returnedUsers)==-1) return false;
// limit length
if ($(".tagit-choice").length >= 5) return false;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With