javascriptjqueryjquery-select2jquery-select2-4

Select2.js v4.0: how set the default selected value with a local array data 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?


Solution

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