0

如何将不在列表中的标签的默认 ID 设置为 0?

[DEMO LINK][1]

关联

在上面的例子中,如果我们从现有中选择,那么它带有 id(1 或 2 或 3),但如果添加新标签并按 Enter 键,则 id 变为文本,我希望 id 设置为新标签的 o 或不从列表中。

怎么做?

4

1 回答 1

0

CreateSearchChoice 应该是您正在寻找的

这是我刚才问过的一个类似的 SO select2 createSearchChoice id from post

createSearchChoice: function (term, data) {
    if ($(data).filter(function () {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            // if not found in current list
            // return {id:term, text:term}

            return {
            id: term,
            text: $.trim(term) + ' (new tag)'
            };

},

请注意,我将 id 设置为新的文本术语,您可以将其设置为像 -1/term 这样的连接值,然后稍后解析它,但术语必须包含在此解决方案的 ID 中

然后在更改事件中,我确定 id 是否为数字(已经存在)。如果它不是数字(在 createsearchchoice 中添加),我将完成发布到标签数据库的过程

.on("change", function(e) {
    if (e.added) { //is it added from select2
    if (isNumeric(e.added.id)){ //did it already exist or createsearchchoice
        add(e.added.id); //it already existed, just add it to the tag list
        } else { //id was created on the fly, post to the database and return a tag id
            $.post('handlers/tags.ashx', { 
               operation:"select2createtag", 
               //because its not numeric, we know id = new tag text
               text: $.trim(e.added.id)} ,   
               function(data){
               //set the added id to the id you just returned from sql
                e.added.id = data.id;
                //...do something else, like then add the new tag to the item

                });
              };
            };

如果您不想发布到 ajax,请让您的服务器端评估您的输入项,以及 id 的任何非数字标签,请遵循上述相同的想法

我在这里更新了你的 Plunker

于 2014-08-19T13:21:45.083 回答