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

时间:2015-07-27 13:19:27

标签: javascript jquery jquery-select2 jquery-select2-4

使用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设为默认选择值?

4 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

这适用于V4.0.3

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

答案 2 :(得分:2)

最好发送另一个属性(在我的案例中选择)进行选择,并使用它来设置默认值。我做了类似下面的事情 -

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);
                }
            });

答案 3 :(得分:1)

这是我的工作。

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