更新select2数据而无需重建控件 [英] Update select2 data without rebuilding the control

查看:402
本文介绍了更新select2数据而无需重建控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将<input type="hidden">转换为select2下拉列表,并通过查询方法向其提供数据

I am converting an <input type="hidden"> to a select2 dropdown and feeding it data through the query method

$('#inputhidden').select2({
    query: function( query ) {
        query.callback( data ); // the data is in the format select2 expects and all works well..
    );
});

问题是我需要破解select2 UI,并在搜索栏顶部放置两个按钮,单击这些按钮将执行ajax调用,并且必须更新select2内容.

The problem is i needed to hack the select2 UI and position two buttons on top of the search bar that, when clicked, will perform ajax calls and will have to update the select2 content.

现在,我需要进行这些更新而不完全重建select2,而只是刷新下拉列表中的项目.我找不到将新数据集传递给已创建的select2控件的方法,这可能吗?

Now, I need those updates to occur without rebuilding the select2 entirely but rather just refreshing the items on the dropdown. I cannot find a way to pass a new set of data to an already created select2 control, is that possible ?

推荐答案

select2 v3.x

如果您有带有选项的本地数组(由ajax调用接收),我认为您应该使用data参数作为返回选择框结果的函数:

select2 v3.x

If you have local array with options (received by ajax call), i think you should use data parameter as function returning results for select box:

var pills = [{id:0, text: "red"}, {id:1, text: "blue"}]; 

$('#selectpill').select2({
    placeholder: "Select a pill",
    data: function() { return {results: pills}; }
});

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
    });
});
$('#newresults').click(function() {
    pills = [{id:0, text: "white"}, {id:1, text: "black"}];
});

字段 : http://jsfiddle.net/RVnfn/576/

如果您使用按钮自定义select2接口,只需在更新后调用updateResults(不允许从select2对象的异地调用此方法,但可以根据需要将其添加到select2中的allowedMethods数组中)方法数据数组(以药丸为例).

In case if you customize select2 interface with buttons, just call updateResults (this method not allowed to call from outsite of select2 object but you can add it to allowedMethods array in select2 if you need to) method after updateting data array(pills in example).

具有附加updateOptions的自定义数据适配器(尚不清楚为什么原始的ArrayAdapter缺少此功能)方法可用于动态更新选项列表(此示例中的所有选项):

Custom data adapter with additional updateOptions (its unclear why original ArrayAdapter lacks this functionality) method can be used to dynamically update options list (all options in this example):

$.fn.select2.amd.define('select2/data/customAdapter',
    ['select2/data/array', 'select2/utils'],
    function (ArrayAdapter, Utils) {
        function CustomDataAdapter ($element, options) {
            CustomDataAdapter.__super__.constructor.call(this, $element, options);
        }
        Utils.Extend(CustomDataAdapter, ArrayAdapter);
        CustomDataAdapter.prototype.updateOptions = function (data) {
            this.$element.find('option').remove(); // remove all options
            this.addOptions(this.convertToOptions(data));
        }        
        return CustomDataAdapter;
    }
);

var customAdapter = $.fn.select2.amd.require('select2/data/customAdapter');

var sel = $('select').select2({
    dataAdapter: customAdapter,
    data: pills
});

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
    });
    sel.data('select2').dataAdapter.updateOptions(pills);
});

字段 : https://jsfiddle.net/xu48n36c/1/

在第4版中,您可以定义可用于本地数据数组的自定义传输方法(例如,@ x @ Caleb_Kiage,我在使用它时没有成功)

in v4 you can define custom transport method that can work with local data array (thx @Caleb_Kiage for example, i've played with it without succes)

docs: https: //select2.github.io/options.html#can-an-ajax-plugin-other-than-jqueryajax被使用

Select2使用ajax.transport中定义的传输方法进行发送 对您的API的请求.默认情况下,此传输方法为jQuery.ajax 但这可以更改.

Select2 uses the transport method defined in ajax.transport to send requests to your API. By default, this transport method is jQuery.ajax but this can be changed.

$('select').select2({
    ajax: {
        transport: function(params, success, failure) {
            var items = pills;
            // fitering if params.data.q available
            if (params.data && params.data.q) {
                items = items.filter(function(item) {
                    return new RegExp(params.data.q).test(item.text);
                });
            }
            var promise = new Promise(function(resolve, reject) {
                resolve({results: items});
            });
            promise.then(success);
            promise.catch(failure);
        }
    }
});

使用此方法,如果数组中的选项文本发生更改-内部select2 dom选项元素列表未修改,则需要更改选项的id.如果数组中的选项ID保持不变-将显示以前保存的选项,而不是从数组中更新!如果仅通过向其添加新项来修改数组,则没问题-可以,在大多数情况下都是如此.

BUT with this method you need to change ids of options if text of option in array changes - internal select2 dom option element list did not modified. If id of option in array stay same - previous saved option will be displayed instead of updated from array! That is not problem if array modified only by adding new items to it - ok for most common cases.

字段: https://jsfiddle.net/xu48n36c/3/

这篇关于更新select2数据而无需重建控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆