Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepopulate values of Select2 (with tagging) doesn't appeare in page

There are numerous discussion about Select2 v4+, and answers which describes prepopulation of selected element. But it seams in my case it's simply doesn't work. Maybe it's because I'm using tag option of Select2. Here is my HTML:

<select class="form-control" id="newProgrTrack" multiple="multiple">
 <option> Sony</option>
 <option> HP</option>
 <option> Dell</option>
 <option> Apple</option>
</select>
<script type="text/javascript">
    $(document).ready(function(){
        $('#newProgrTrack').select2({
            placeholder: "Select a brands or add one, by typing in",
            tags: true,
            // tokenSeparators: [',', ' ']
        });
    });
</script>

I get ajax response from server in JSON which describes, which options are already chosen. So I need to prepopulate them in select2 as tags for user. Farther user should have oppty to add or delete options from the option list and also add new one, which is not available as select options as for now.

brands: ['Sony','Dell'] //server response

So as far as I'll get new select options from user all the time, I'd like not to stick to value attribute, but to text of tag (however I try both). Most close that I get was Jquery code bellow (after select2 initialization):

$('#newProgrTrack').val(['Sony', 'Dell']);

When I console.log after - I get array with ['Sony', 'Dell'], but this tags didn't appear on HTML page. Pls help.

like image 228
Yevhen Avatar asked Feb 07 '23 20:02

Yevhen


2 Answers

$('#newProgrTrack').val(['Sony', 'PQRS']).trigger('change');

you have to manually trigger change method

like image 146
Raja Sekar Avatar answered Feb 13 '23 16:02

Raja Sekar


The Programmatic control chapter of the official documentation covers this in the Add, select or clear item section.

https://select2.org/programmatic-control/add-select-clear-items

For Appending Items:

Create if not exists

You can use .find to select the option if it already exists, and create it otherwise:

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

For pre-populating the select2 control with a previously stored value, you'll want to follow the appropriate directions for your data source. In your case, it looks like you are inlining the values instead of using ajax, so the following section applies.

Selecting options

To programmatically select an option/item for a Select2 control, use the jQuery .val() method:

$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed 

You can also pass an array to val make multiple selections:

$('#mySelect2').val(['1', '2']); $('#mySelect2').trigger('change'); //Notify any JS components that the value changed 

Select2 will listen for the change event on the element that it is attached to. When you make any external changes that need to be reflected in Select2 (such as changing the value), you should trigger this event.

like image 34
J E Carter II Avatar answered Feb 13 '23 16:02

J E Carter II