在select2列表中输入文本



我正在开发一个使用Select2插件的应用程序。我需要允许用户在框中键入以显示供他们选择的选项。我有工作。但是,我也想让用户能够在列表中输入新的选项。我不知道该怎么做。目前,我的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 }
});

createSearchChoice选项就是您想要的。

来自文件:

从用户的搜索词中创建一个新的可选选项。允许创建无法通过查询功能获得的选项。当用户可以动态创建选择时很有用,例如"标记"用例。

在该功能中,您可以选择检查用户是否未在现有元素中键入,然后用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。

当前您正在通过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

最新更新