Select2.js v4.0:如何使用本地数组数据源设置默认选择值

Select2.js v4.0: how set the default selected value with a local array data source?

本文关键字:数据源 数组 设置 默认 选择 v4 js 何使用 Select2      更新时间:2023-09-26

通过使用select2.js v4插件,当我使用本地数组数据为源时,如何设置默认选择值?

例如

,代码为

var data_names = [{
  id: 0,
  text: "Henri",
}, {
  id: 1,
  text: "John",
}, {
  id: 2,
  text: "Victor",
}, {
  id: 3,
  text: "Marie",
}];
$('select').select2({
  data: data_names,
});

如何设置id 3作为默认选择值?

$('.select').select2({
        data: data_names,
    }).select2("val",3);

这在V4.0.3中适用

$('.select').select2({
    data: data_names,
})
$('select').val(3);
$('select').trigger('change.select2');

最好发送另一个属性(在我的情况下选中)用于select并使用它来设置默认值。我做了如下操作-

var data_names = [{
  id: 0,
  text: "Henri",
}, {
  id: 1,
  text: "John",
}, {
  id: 2,
  text: "Victor",
}, {
  id: 3,
  text: "Marie",
  selected: true
}];

那么做

            $(".select").select2({
                data : data_names
            });
            data_names.forEach(function(name){
                if(name.selected) { 
                   $(".select").select2('val',name.id);
                }
            });

这对我来说很有效。

$('#select').select2({data: data_names}).val(3).trigger('change')