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

13,287

Solution 1

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

Solution 2

this worked for me with V4.0.3

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

Solution 3

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

Solution 4

It's workerd for me.

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

Share:
13,287
Admin
Author by

Admin

Updated on June 13, 2022

Comments

  • Admin
    Admin about 2 years

    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?

  • Paul
    Paul about 7 years
    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/…
  • temuri
    temuri about 3 years
    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.