select2 init with data code example

Example 1: select2 add option

// Set the value, creating a new option if necessary
if ($('#mySelect2').find("option[value='" + data.id + "']").length) {
    $('#mySelect2').val(data.id).trigger('change');
} else { 
    // Create a DOM Option and pre-select by default
    var newOption = new Option(data.text, data.id, true, true);
    // Append it to the select
    $('#mySelect2').append(newOption).trigger('change');
}

Example 2: select2

$('.js-example-basic-single').select2({
  placeholder: 'Select an option'
});

Tags:

Misc Example