选择2 createSearchChoice并删除已创建的选项

时间:2014-12-17 17:40:53

标签: jquery-select2

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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

createSearchChoice:

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 };
}

on'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