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

4

7

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?

Watchdog answered 27/7, 2015 at 13:19 Comment(2)
$("#id").select2().select2("val", 'oneofthevaluehere');Wojak
As of v4.1 just do {id: 3, text: "Marie", selected: true}.Neck
T
7
$('.select').select2({
        data: data_names,
    }).select2("val",3);
Teaser answered 28/7, 2015 at 18:11 Comment(0)
D
5

this worked for me with V4.0.3

$('.select').select2({
    data: data_names,
})
$('select').val(3);
$('select').trigger('change.select2');
Distract answered 21/4, 2017 at 13:22 Comment(1)
This is the correct answer for v4. More compactly you can write $('.select').val(3).trigger('change'). Use trigger('change.select2') to notify only Select2 of the change. See select2.github.io/…Chondro
S
4

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);
                }
            });
Shig answered 10/12, 2017 at 16:21 Comment(1)
This is the correct answer for version 4.1. All you need is "selected: true" on your data element, should not trigger any events or call an API method.Neck
S
2

It's worked for me.

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

Sundae answered 22/5, 2018 at 9:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.