kasper Taeymans kasper Taeymans - 4 months ago 55x
jQuery Question

How to modify jquery tag-it plugin: limit number of tags and only allow available tags

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) {

                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

            var sampleTags = ['php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python'];

            // Tag events
            var eventTags = $('#s_tags');
                availableTags: sampleTags,
                caseSensitive: false,
                onlyAvailableTags: true,