jQuery Select2:init后如何设置数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15454383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:05:18  来源:igfitidea点击:

Select2: how to set data after init?

javascriptjqueryjquery-select2

提问by Erik

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

我需要在初始化 select2 后设置一组数据。所以我想做这样的事情:

var select = $('#select').select2({});
select.data([
  {id: 1, text: 'value1'},
  {id: 1, text: 'value1'}
]);

But I get the following error:

但我收到以下错误:

Option 'data' is not allowed for Select2 when attached to a element.;

附加到元素时,Select2 不允许使用选项“数据”。

My HTML:

我的 HTML:

<select id="select" class="chzn-select"></select>

What should I use instead of a select element?

我应该使用什么来代替 select 元素?

I need to set the source of items for search

我需要设置搜索项的来源

回答by PSR

In onload:

在加载中:

$.each(data, function(index, value) {
  $('#selectId').append(
    '<option value="' + data[index].id + '">' + data[index].value1 + '</option>'
  );
});

回答by Kelz

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.

创建一个<input type="hidden">元素并将 select2 绑定到该元素。在常规选择框上使用 .select2 不会让您处理数据,它主要为您提供 UI 和后选择方法。

Source: Select2 Documentation

来源: Select2 文档

回答by JTvermose

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

来源: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');

回答by tuanngocptn

You can rerender and trigger the select2

您可以重新渲染并触发 select2

render select2

渲染选择2

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

after need to change the data 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').select2('destroy');
$('.select2').empty();
$('.select2').select2({
  placeholder: 'Slect value',
  allowClear: true,
  data: dataChange
});

trigger select2

触发选择2

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

Hope this is the answer for you :3

希望这是你的答案:3

回答by FranBran

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

对于 v4,您必须使用更新的数据销毁和重建 select2。检查https://github.com/select2/select2/issues/2830

回答by davidisnotnull

I've recently had the scenario where changing one select2 object alters the contents of a second (parent - child groupings effectively). I used an ajax call to retrieve a new set of Json data, which was then picked up by the second select2 object. I've included the code below:

我最近遇到了这样一种情况,即更改一个 select2 对象会改变第二个对象的内容(有效地父 - 子分组)。我使用 ajax 调用来检索一组新的 Json 数据,然后由第二个 select2 对象拾取。我已经包含了下面的代码:

 $("#group").on('change', function () {
        var uri = "/Url/RetrieveNewResults";
        $.ajax({
            url: uri,
            data: {
                format: 'json',
                Id: $("#group :selected").val()
            },
            type: "POST",
            success: function (data) {
                $("#groupchild").html('');
                $("#groupchild").select2({
                    data: data,
                    theme: 'bootstrap',
                    placeholder: "Select a Type"
                });
            },
            error: function () {
                console.log("Error")
            }
        });
    });

I found that I had to include the $("#groupchild").html('') in order to clear out the previous set of data in the second select2. Hope this helps.

我发现我必须包含 $("#groupchild").html('') 以清除第二个 select2 中的前一组数据。希望这可以帮助。

回答by Luesak Luesukprasert

Here's what I did.

这就是我所做的。

1. Extend select2

1.扩展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)

2. 像往常一样初始化(例如 --- 你的可能不同)

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

3. 通过调用新的扩展函数 func 动态设置 Ajax 选项

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