如何在select2中添加新标签?

时间:2015-04-13 10:42:47

标签: javascript jquery ajax jquery-select2

我正在尝试从我的api获取标签。一切正常但我无法添加新标签。这是我试过的:

$(function(){
        var user_email = localStorage.getItem('email');
        var api = localStorage.getItem("user_api_key");
        var auth = "apikey" +' ' +(user_email+":"+api);
        $('#s2id_id_add-places').select2({
            multiple: true,
            tags: [],
            tokenSeparators: [",", " "],
            width: "200px",
            ajax: {
                placeholder: "Click to enter who",
                type: "GET",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", auth);
                    xhr.setRequestHeader("Content-Type","application/json");
                    xhr.setRequestHeader("Accept","application/json");
                },
                url: "https://example.com/api/v3/places/",
                dataType: "json",
                contentType: "application/json",
                processData: true,
                quietMillis: 50,
                data: function(term) {
                    return {
                        term: term
                    };
                },
                results: function(data) {
                    var results = [];
                    if(data.objects.length > 0) {
                        for (i=0; i<data.objects.length; i++) {
                            results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
                        }
                    }
                    return {
                        results: results
                    };
                },
    });
    });

通过使用上面的代码,我只能获取标签,但我无法添加新标签。我该如何添加新标签?

请帮忙

1 个答案:

答案 0 :(得分:1)

$("#e11_2").select2({
  createSearchChoice: function(term, data) { 

      if ($(data).filter( function() { 
           return this.text.localeCompare(term)===0;   
      }).length===0) {
           return {id:term, text:term};
      } 
  },
  multiple: true,
  data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});

你必须创建一个像createSearchChoice这样的函数,它返回一个带有'id'和'text'的对象。在其他情况下,如果您返回undefined,则不会创建选项。