【问题标题】:Select2 createSearchChoice and removing already created choicesSelect2 createSearchChoice 并删除已创建的选项
【发布时间】:2015-02-16 08:31:42
【问题描述】:

我正在尝试自定义 select2,并且我正在覆盖 createSearchChoice 以在未找到该项目时返回一个对象。

然后.on('select2-selecting', 我将采用新创建的选择并将其转换为“真实”对象(持续到服务器)。但是,现在创建的“临时”选项与对象不匹配,因此 select2 仍将搜索项显示为选项,因为我创建了一个新的不同对象并将搜索选项视为临时实体。

如何阻止 select2 从结果中附加任何以前创建的搜索选项? (理想情况下,我希望从“了解”先前创建的搜索选项中清除 select2)

【问题讨论】:

  • 我认为问题是id 值不匹配。您在createSearchChoice 和服务器上将id 设置为什么?也许您可以显示您的 createSearchChoice.on('select2-selecting' 代码。另外,这是单选还是多选?由<select><input type="hidden"> 支持?是否通过 ajax 检索选项?

标签: jquery-select2


【解决方案1】:

Select2 不会认为这两个项目相同,除非它们具有相同的 id 值。

也许您可以延迟选择新项目,直到它被持久化到服务器之后。服务器必须返回它使用的 id 值。

创建搜索选择:

createSearchChoice: function(term) {
    // We need to make sure the 'select2-selecting' event handler
    // can identify a "temporary" item.
    return { id: '_TEMP_', text: term, isTemp: true };
}

关于'select2-selecting':

.on('select2-selecting', function(e) {
    var $select = $(this),
        item = e.choice;
    if (item.isTemp) {
        e.preventDefault(); // Prevent the item from immediately being selected.
        $.ajax({ // This is the ajax call that persists the new item.
            ...,
            data: { newText: item.text }, // Item text is passed to the server
            success: function(item) { // The server returns the new item.
                // Add the item to the selection.
                // Note: This assumes a multiple select.
                var data = $select.select2('data');
                data.push(item);
                $select.select2('data', data);
            },
            complete: function() {
                $select.select2('close');
            }
        });
    }
})

jsfiddle

对于单个选择,success 回调将更改为:

success: function(item) {
    $select.select2('data', item);
},

注意:对于单选,即使选择了新选项,它也会出现在下拉列表中,因为这是单选的工作方式。

jsfiddle

【讨论】:

  • 非常感谢,id 让我受益匪浅。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
  • 2020-03-31
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多