将文本输入 select2 列表

Inputing text into select2 list

我正在开发一个使用 Select2 插件的应用程序。我需要允许用户在框中输入内容以显示选项 select。我有那个工作。但是,我还想让用户能够在列表中输入新选项。我不知道该怎么做。目前,我的 Select2 初始化如下所示:

$('#myField').select2({
  allowClear: true,
  placeholder: 'Please select',
  minimumInputLength: 3,
  initSelection: function (element, callback) {
    var id = $(element).val();
    if (id) {
      callback({ ItemId: id, ItemText: selectedName });
    }
  },
  ajax: {
    url: '/api/suggestions',
    dataType: 'json',
    quietMillis: 150,
    data: function (term, page) {
      return {
        q: term,
        count: 3
      }
    },
    results: function (data, page) {
      return { results: data, id: 'ItemId', text: 'ItemText' };
    }
  },
  id: function (item) { return item.ItemId; },
  text: function (item) { return item.ItemText; },
  formatResult: function (i) { return i.ItemText },
  formatSelection: function (i) { return i.ItemText }
});

目前您正在通过 Select2 上的 ajax 选项加载数据,如果您在 Select2 初始化之前预加载数据,则可以解决该问题,例如:

var data = $.get('/api/suggestions');

然后使用您之前创建的数据变量初始化 Select2。

比做一些用户将以某种方式添加数据并将它们附加到 data 变量的实现:

data.push({ id : 'newID' , text : 'newText'});

现在您获得了新数据,所以只需重新加载您的 Selet2 即可:

$('#myField').select2('data', data);

编辑:

如果不预加载数据,您可以这样做:

var data = $("#myField").select2('data'); //Read all data from select2
data.push({id:5,text:"new item"}); //Add new item to data array
$("#myField").select2("data", data, true); //Update select2 data

createSearchChoice 选项就是您要找的。

来自documentation

Creates a new selectable choice from user's search term. Allows creation of choices not available via the query function. Useful when the user can create choices on the fly, eg for the 'tagging' usecase.

在此函数中,您可以选择检查用户是否未在现有元素中键入内容,然后使用 custom 标志标记此新项目,以便稍后在已更改的事件中创建项目:

createSearchChoice: function (term, data) {
    //optionally check that the item is not already in the list
    if ($(data).filter(function () {
        return this.ItemText.localeCompare(term) === 0;
    }).length === 0) {
        return {
            ItemId: term,
            ItemText: term,
            custom: true // mark the item
        };
    }
}

然后在 "change" 事件中,当 custom 标志存在时,您可以处理新元素的保存

.on("change", function (evt) {
    if (evt.added) {
        console.log(evt.added)
        if (evt.added.custom) {
            //save to server, etc.
        }
    });

演示 JSFiddle.