-1

是否可以设置 select2 控件以在单选模式下接受自定义选择(标签:假)?

在搜索框中输入您的选择而不是看到“未找到结果”时,只需查看您输入的内容并通过单击或按 Enter 选择它。

4

1 回答 1

1

好吧 - 我终于自己找到了解决方案。每次您输入并删除以前的临时选择时,我都会覆盖原始 SelectAdapter 添加新选择:

$.fn.select2.amd.require(['select2/data/select', 'select2/utils'],
function (SelectAdapter, Utils) {
function XSelectAdapter($element, options) {
    XSelectAdapter.__super__.constructor.call(this, $element, options);
}

Utils.Extend(XSelectAdapter, SelectAdapter);

XSelectAdapter.prototype.query = function (params, callback) {
    var data = [];
    var self = this;
    var $options = this.$element.children();
    var have_exact_match = false;

    $options.each(function () {
        var $option = $(this);
        if (!$option.is('option') && !$option.is('optgroup')) {
            return;
        }
        var option = self.item($option);

        if (option.xtemp === true) {
            $(this).remove(); // previously typed-in choice - delete
            return;
        }
        if (option.term === params.term) {
            have_exact_match = true; // will not choice if have exact match
        }

        var matches = self.matches(params, option);
        if (matches !== null) {
            data.push(matches);
        }
    });

    if (!have_exact_match) {
        self.addOptions(this.option({selected: false, id: params.term, text: params.term, xtemp: true}));
        data.push({selected: false, id: params.term, text: params.term});
    }

    callback({
        results: data
    });
    };

    $('#your_select2').select2({dataAdapter:XSelectAdapter});
});
于 2015-05-23T13:43:33.880 回答