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

kasper Taeymans picture kasper Taeymans · Sep 21, 2011 · Viewed 10.3k times · Source

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.

Answer

kasper Taeymans picture kasper Taeymans · Sep 21, 2011

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,

            })

        });