Select2: how to set data after init?

后端 未结 7 1870
醉梦人生
醉梦人生 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;
                },
            });
    
    0 讨论(0)
  • 2021-02-06 22:48

    Source: https://select2.org/programmatic-control/add-select-clear-items

    Add item:

    var data = {
        id: 1,
        text: 'Barn owl'
    };
    
    var newOption = new Option(data.text, data.id, false, false);
    $('#mySelect2').append(newOption).trigger('change');
    

    Clear items:

    $('#mySelect2').val(null).trigger('change');
    
    0 讨论(0)
  • 2021-02-06 22:56

    For v4 you'll have to destroy and reconstruct select2 with updated data. Check https://github.com/select2/select2/issues/2830

    0 讨论(0)
  • 2021-02-06 22:59

    You can rerender and trigger the select2

    render select2

    $('.select2').select2({
      placeholder: 'Slect value',
      allowClear: true
    });
    

    after need to change the data data

    let dataChange = [
      {
        id: 0,
        text: 'enhancement'
      },
      {
        id: 1,
        text: 'bug'
      },
      {
        id: 2,
        text: 'duplicate'
      },
      {
        id: 3,
        text: 'invalid'
      },
      {
        id: 4,
        text: 'wontfix'
      }
    ];
    

    rerender the select2

    $('.select2').select2('destroy');
    $('.select2').empty();
    $('.select2').select2({
      placeholder: 'Slect value',
      allowClear: true,
      data: dataChange
    });
    
    

    trigger select2

    $('.select2').trigger('change');
    

    Hope this is the answer for you :3

    0 讨论(0)
  • 2021-02-06 23:01

    In onload:

    $.each(data, function(index, value) {
      $('#selectId').append(
        '<option value="' + data[index].id + '">' + data[index].value1 + '</option>'
      );
    });
    
    0 讨论(0)
  • 2021-02-06 23:01

    Make an <input type="hidden"> element and bind select2 to that. Using .select2 on a regular select box doesn't let you play with the data, it just mostly gives you the UI and post-selection methods.

    Source: Select2 Documentation

    0 讨论(0)
提交回复
热议问题