修改jquery标记的行为 - 基于自动完成库来使用ajax JSON源

rey*_*n64 4 tags jquery jquery-ui jquery-ui-autocomplete tag-it

我正在尝试为jQuery插件标签添加一些功能- 它基于自动完成:

a)我尝试过滤我的JSON数据以仅显示标记的名称.

返回的JSON示例/repo/json:

[{id:1, name:"0.8-alpha-1", category:"version"}, {id:2, name:"0.8-alpha-2", category:"version"}, {id:3, name:"0.8-alpha-3", category:"version"}, {id:4, name:"0.8-alpha-4", category:"version"}, {id:5, name:"0.8-alpha-1", category:"version"}, {id:6, name:"0.8-alpha-2", category:"version"}, {id:7, name:"0.8-alpha-3", category:"version"}, {id:8, name:"0.8-alpha-4", category:"version"}]
Run Code Online (Sandbox Code Playgroud)

b)我想在用户提交数据时提交标签的id,而不是名称.

c)我尝试在我的tag-it输入字段中添加一些约束:用户无法验证不在我返回的JSON中的标记/repo/json call.

我不想fork tag-it存储库,似乎可以测试用户数组和搜索beforeTagAdded选项之间的交集.

我此时尝试没有成功,因为我不知道在哪里可以找到实现交集的标签列表.

我的js代码:

 $(function(){
    $("#singleFieldTags").tagit({
      tagSource: function(search, showChoices) {
        $.ajax({
          url: "/repo/json",
          dataType:   "json",
          data: {q: search.term},
          success: function(choices) {
            showChoices(choices);
          }
        })},
           beforeTagAdded: function(event, ui) {
           //if ($.inArray(ui.tagLabel, search) == -1) {
           //   $("#singleFieldTags").tagit("removeTagByLabel", ui.tagLabel);
           // }
            console.log(ui.tag);
           }});

    });
Run Code Online (Sandbox Code Playgroud)

html表单:

<form name="data" action="/repo/uploadMole" method="POST" enctype="multipart/form-data">
    <input name="tags" id="singleFieldTags" ><br/>
    <input type="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)

Chr*_*ing 5

你要求你提交一些不同的东西.然后让我们采取单一的入口点:

$('#data').submit(function() {
    // Change the value we are submitting
    var tagids = [];
    $.each($('#singleFieldTags').val().split(','),
           function(idx, taglabel){
               tagids.push(lookup_tagid_for_label(taglabel));
           }
    )
    $('#singleFieldTags').val(tagids.join(','));          
    return true; // Let the event go on.
});
Run Code Online (Sandbox Code Playgroud)

这应该在提交之前使用ID更改标签.

lookup_tagid_for_label,可以再次进行ajax调用,但在首次查找时将其缓存在字段上可能更便宜:

$("#singleFieldTags").tagit({
     autocomplete: {
        source: function(search, showChoices) {
                    $.getJSON("/repo/json", {q: search.term},
                        function (data) {
                            var choices = [];
                            $.each(data, function (idx, tag) {
                                choices.push(tag.name);
                                $("#singleFieldTags").data(tag.name, tag.id);
                            });
                            showChoices(choices);
                    });
                }
});
Run Code Online (Sandbox Code Playgroud)

然后你就可以替换lookup_tagid_for_label(taglabel)使用$("#singleFieldTags").data(taglabel).

与我的另一个答案相反,那个预期的标签 - 它遵循autocomplete-api,现在可行.