Select2: how to set data after init?

后端 未结 7 1884
醉梦人生
醉梦人生 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: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');
    

提交回复
热议问题