jquery - 如何修改jquery tag-it插件: limit number of tags and only allow available tags

标签 jquery jquery-ui tag-it

如何修改tag-it ui插件https://github.com/aehlke/tag-it (版本 v2.0)因此它只允许选择 x 个标签,以及如何仅允许“availableTags-option”中的标签?

这个问题(或其第一部分)过去已经被问过并询问过,但针对的是以前版本的插件。

最佳答案

首先将自定义选项(maxTags 和 onlyAvailableTags)添加到插件文件中,如下所示...

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
        }

接下来用这个函数替换 _isNew 函数...

_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;
        }

现在您可以在初始化 tagit 时使用这些选项。仅允许使用示例标签,最多 3 个标签

$(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,

            })

        });

关于jquery - 如何修改jquery tag-it插件: limit number of tags and only allow available tags,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7500187/

相关文章:

jquery - 浏览器兼容性问题

javascript - 如何在移动版本中单击导航链接时隐藏引导菜单

javascript - 获取 - 追加并查找具有类名的 div

javascript - jQuery Tag-It - 使用标签和值对象列表

c# - 无法从 "jQuery Tag-it!"获取标记

jquery - 如何限制jquery中的tag-it输入

jquery - 试图在 IE6 中调整 jQuery 对话框的大小?

javascript - jQuery - 任何时候只显示一个 div

javascript - 如何在 JQuery ui 中正确使用 AppendTo 和 Draggable() ?

javascript - jQuery UI Tabs 可以加载新的完整 HTML 页面吗?