javascript Select2:使用代码动态添加新标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27844227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:04:49  来源:igfitidea点击:

Select2: add new tag dynamically using code

javascriptjquery-select2

提问by webber

I'm using select2 for tagging and I have it setup such that a user can add new tags as well. The issue that I'm dealing with is validating the user entry and adding the sanitized tag to selection.

我正在使用 select2 进行标记,并对其进行了设置,以便用户也可以添加新标签。我正在处理的问题是验证用户条目并将经过消毒的标签添加到选择中。

To be more specific, when a user enters a space in a tag, i use formatNoMatches to display a js link to sanitize the tag and then add the tag programmatically. This code seems to run without errors but when sanitize is called all selections of the input are cleared.

更具体地说,当用户在标签中输入空格时,我使用 formatNoMatches 显示一个 js 链接来清理标签,然后以编程方式添加标签。这段代码似乎没有错误地运行,但是当调用 sanitize 时,所有输入的选择都会被清除。

Any clues where i might be going wrong?

我可能会出错的任何线索?

var data=[{id:0,tag:'enhancement'},{id:1,tag:'bug'},{id:2,tag:'duplicate'},{id:3,tag:'invalid'},{id:4,tag:'wontfix'}];
function format(item) { return item.tag; }

function sanitize(a){

    $("#select").select2('val',[{
        id: -1,
        tag: a
      }]);

      console.log(a);
};

$("#select").select2({
  tags: true,
  // tokenSeparators: [",", " "],
  createSearchChoice: function(term, data) {
    return term.indexOf(' ') >= 0 ?  null :
    {
        id: term,
        tag: term
      };
  },
  multiple: true,
  data:{ results: data, text: function(item) { return item.tag; } },  formatSelection: format, formatResult: format,
  formatNoMatches: function(term) { return "\"" + term + "\" <b>Is Invalid.</b> <a onclick=\"sanitize('"+ term +"')\">Clear Invalid Charecters</a>" }
});

回答by webber

After hacking on it some more i realized that I should be setting the new item to the "data" property and not value.

在对其进行了更多修改后,我意识到我应该将新项目设置为“数据”属性而不是值。

var newList = $.merge( $('#select').select2('data'), [{
        id: -1,
        tag: a
      }]);
$("#select").select2('data', newList)

回答by Roman Yakoviv

Only this solution works for me:

只有这个解决方案对我有用:

function convertObjectToSelectOptions(obj){
    var htmlTags = '';
    for (var tag in obj){
        htmlTags += '<option value="'+tag+'" selected="selected">'+obj[tag]+'</option>';
    }
    return htmlTags;
}
var tags = {'1':'dynamic tag 1', '2':'dynamic tag 2'}; //merge with old if you need
$('#my-select2').html(convertObjectToSelectOptions(tags)).trigger('change');

回答by Athlan

You can set new value (if tags you can pass array) and trigger 'change' event.

您可以设置新值(如果标签可以传递数组)并触发“更改”事件。

var field = $('SOME_SELECTOR');

field.val(['a1', 'a2', 'a3']) // maybe you need merge here
field.trigger('change')

About events: https://select2.github.io/options.html#events

关于事件:https: //select2.github.io/options.html#events