Select2: how to set data after init?

后端 未结 7 1878
醉梦人生
醉梦人生 2021-02-06 22:33

I need to set an array of data after initializing select2. So I want to make something like this:

var select = $(\'#select\').select2({});
select.data([
  {id: 1         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-06 22:42

    Here's what I did.

    1. Extend select2

        Select2.prototype.setAjax = function (ajaxOptions)
                    {
                        // Set the new ajax properties
                        var oAjaxOpts = this.options.get('ajax');
                        if (oAjaxOpts != undefined && oAjaxOpts != null)
                        {
                            for (var sKey in ajaxOptions)
                            {
                                oAjaxOpts[sKey] = ajaxOptions[sKey];
                            }
                        }
                        var DataAdapter = this.options.get('dataAdapter');
                        this.dataAdapter = new DataAdapter(this.$element, this.options);
                    }
    

    2. Initialize as usual (for example --- yours could be different)

    jHtmlFrag.select2({
                dropdownParent: $(oData.jDiv),
                placeholder: "Select Option",
                allowClear: true,
                minimumInputLength: 2,
                ajax: {
                    url: "",
                    method: "POST",
                    dataType: 'json',
                    delay: 250,
                    processResults: function (oResults, params)
                    {
                        let page = params.page || 1;
                        // console.log(oResults, (params.page * 10));
                        return {
                            results: oResults.data,
                            pagination: {
                                more: (page * 10) < oResults.recordsFiltered
                            }
                        };
                    }
                }
            }).val(null).trigger('change');
    

    3. Set Ajax options dynamically when you feel like by calling the new extension func

    jCombo.select2('setAjax', {
                url: sUrl,
                data: function (params)
                {
                    let query = {
                        search: params.term,
                        type: params._type,
                        page: params.page || 1,
                    }
                    return query;
                },
            });
    

提交回复
热议问题