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

Romeo picture Romeo · Jul 27, 2015 · Viewed 11.7k times · Source

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?

Answer

lambdaDev picture lambdaDev · Jul 28, 2015
$('.select').select2({
        data: data_names,
    }).select2("val",3);