最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

By using select2.js v4 plugin , how set the default selected value when I use a local array data for source?

for example with this code

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

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

How set id 3 as the default selected value?

By using select2.js v4 plugin , how set the default selected value when I use a local array data for source?

for example with this code

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

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

How set id 3 as the default selected value?

Share Improve this question asked Jul 27, 2015 at 13:19 RomeoRomeo 811 gold badge1 silver badge4 bronze badges 2
  • $("#id").select2().select2("val", 'oneofthevaluehere'); – cfprabhu Commented Jul 27, 2015 at 13:33
  • As of v4.1 just do {id: 3, text: "Marie", selected: true}. – temuri Commented Apr 3, 2021 at 15:21
Add a comment  | 

4 Answers 4

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

this worked for me with V4.0.3

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

It is better you send another attribute (selected in my case below) for select and use it to set the default value. I did something like below -

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

then do

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

It's worked for me.

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

发布评论

评论列表(0)

  1. 暂无评论