jQuery tag-it 只允许可用的标签。

9

我在我的脚本中使用了 jQuery tag-it

$("#user_autocomplete").tagit({
    tagSource: function (request, response) {
        $.ajax({
            data: {
                term: request.term
            },
            type: "POST",
            url: "/site2/message/users.php",
            dataType: "json",
            success: function (data) {
                response($.map(data, function (item) {
                    return {
                        label: item,
                        value: item
                    }
                }));
            }
        });
    },
    tagLimit: 3,
    autocomplete: {
        delay: 0,
        minLength: 1
    },
});

在这种情况下,所有输入字段都被确认了。但我只想添加可用的字段。怎么做?

你能解释得更详细些吗?你所说的“只有可用字段”是什么意思? - Purus
感谢您添加自己的解决方案。我已将其移动到答案中;如果您希望在将来为自己的问题提供解决方案,最好像这样自我回答。 - halfer
2个回答

13

代表原帖发布:

我正在使用beforeTagAdded函数,我找到了答案:

        tagSource: function(request, response) 
        {
            $.ajax({
                data: { term:request.term },
                type: "POST",
                url:        "/site2/message/users.php",
                dataType:   "json",
                 success: function( data ) {
                     array = data;
                    response( $.map( data, function( item ) {

                        return {
                            label:item,
                            value: item
                        }
                        }));
                    }

            });
            },
        tagLimit :3,
        autocomplete: {delay: 0, minLength: 1},
        beforeTagAdded: function(event, ui) {
            if(array.indexOf(ui.tagLabel) == -1)
            {
                return false;
            }
            if(ui.tagLabel == "not found")
            {
                return false;
            }

        },

@Kakitori:我只是代表原帖发布了这个帖子——如果你喜欢它,也许可以考虑给原帖点赞? - halfer
谢谢您分享这份快乐(已经点赞原帖了 ;))!您应该考虑向原项目提交一个拉取请求 :) - Erdal G.

0
我通过在createTag函数顶部添加以下检查来实现这一点:
if (this.options.onlyAvailableTags && $.inArray(this._formatStr(value), this.options.availableTags) == -1) {
    return false;
}

然后在 tag-it 调用中添加此选项:

onlyAvailableTags: true

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接