Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
Romeo Avatar asked Jul 27 '15 13:07

Romeo


People also ask

How do I assign a value to Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

How can I set the initial value of Select2 when using Ajax?

var initial_creditor_id = "3"; $(". creditor_select2"). select2({ ajax: { url: "/admin/api/transactions/creditorlist", dataType: 'json', delay: 250, data: function (params) { return { q: params. term, c_id: initial_creditor_id, page: params.

How do I create a Select2 dynamically?

HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


2 Answers

$('.select').select2({
        data: data_names,
    }).select2("val",3);
like image 137
lambdaDev Avatar answered Oct 12 '22 16:10

lambdaDev


this worked for me with V4.0.3

$('.select').select2({
    data: data_names,
})
$('select').val(3);
$('select').trigger('change.select2');
like image 38
user3454847 Avatar answered Oct 12 '22 15:10

user3454847