【问题标题】:Inputing text into select2 list将文本输入到 select2 列表中
【发布时间】:2015-02-10 14:38:48
【问题描述】:

我正在开发一个使用 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 }
});

【问题讨论】:

    标签: jquery jquery-select2


    【解决方案1】:

    createSearchChoice 选项是您正在寻找的。​​p>

    来自documentation

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

    在此函数中,您可以选择检查用户是否未在现有元素中键入,然后使用 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.

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我无法预加载数据。它根据用户输入的内容提出了一些建议。还有其他想法吗?
      猜你喜欢
      • 1970-01-01
      • 2017-06-06
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多