限制jQuery中的输入标签数量

时间:2011-02-14 18:15:54

标签: jquery

我一直在寻找一个jQuery自动建议标签(类似于stackoverflow标签输入)插件,它限制了输入标签的数量(例如,不允许创建超过5个标签?)。如果有人知道这样的插件,或kind enough to modify this code限制标签的数量,我会非常感激。

4 个答案:

答案 0 :(得分:3)

确定改变了Tag It插件......

首先打开插件js文件并找到is_new函数(朝向文件底部)...

用这个替换整个函数:

    function is_new (value){
        var is_new = true;
        var count = 0;
        this.tag_input.parents("ul").children(".tagit-choice").each(function(i){
            count++;
            n = $(this).children("input").val();
            if (value == n || count >= options.maxTags) {
                is_new = false;
            }
        })
        return is_new;
    }

注意我只添加了count变量并修改了循环中的if语句,以检查count是否为> =选项maxTags

然后当你调用插件时,设置maxTags选项:

    $('#tagBox').tagit({
        availableTags: '../Tag/GetTags',
        maxTags: 5
    });

容易!

答案 1 :(得分:0)

我没看过你的代码,但是我假设你有一个约定用于分隔标签是什么(空格,逗号,其他),所以你可以跟踪dlimiters的数量然后不允许它们输入已输入第5个分隔符。

答案 2 :(得分:0)

This one看起来不错。查看selectionLimit属性。

答案 3 :(得分:0)

以防其他人使用最新版本的tag-it ,以下是解决方案:)ENJOY!

_isNew: function(value) {
        var that = this;
        var isNew = true;
        //JAVI ADDED NEXT LINE
        var count = 0;
        this.tagList.children('.tagit-choice').each(function(i) {
            //JAVI ADDED NEXT LINE AND MODIFIED IF (ADDING SECOND CONDITION)
            count++;
            if (that._formatStr(value) == that._formatStr(that.tagLabel(this)) || count >= that.options.maxTags) {
                isNew = false;
                return false;
            }
        });
        return isNew;
    },
相关问题