Select2: loading selected values

Select2: loading selected values

Problem Description:

Im trying to load the selected values from the database into my multiple select box.

When I load the option initially from the database, It work perfect.

enter image description here

But I would like to add the SELECTED items for this rrecord.
I’ve tried a few approaches which is a bit hacky, like this.

                var keywordArray = new Array();
                keywordArray = test[0].keyword.split(",");

                for( var x = 0; x < keywordArray.length ; x++){
                    foundKeyword = $( "select" ).find("option[value="+keywordArray[x]+"]").text();
                    $('.select2-choices').prepend("<li class='select2-search-choice'><div>" + foundKeyword + "</div><a href='#' class='select2-search-choice-close' tabindex='-1'></a></li>");
                    $('.select2-search-field input').attr("aria-activedescendant","select2-result-label-25");
                    $('.select2-search-field input').css("width", "10px");
                    $('.select2-search-field input').removeClass("select2-default");


This CANT be how its done, and besides it does not work propperly

enter image description here

even though the SELECTED keywords appear to be there. You cant delete them and the associated value in the dropdown is still selectable (not greyed out).

Ive tried a example from the net as-well, Which did not work

                var pills = [{id:0, text: "ECHO"}, {id:1, text: "BRAVO"}];

                    placeholder: "Select a pill",
                    data: function() { return {results: pills}; }

So my question is, how do you load the SELECTED data from the DB and refresh or re-initialise the select2 selected area? This also needs to disable the select capability of items already selected.

Solution – 1

So after a little help from Mr Arun P Johny,
I finaly got to the very simple answer.

Maybe I dont fully grasp it yet, but is I understand correctly, you have to approach the loading differently depending if you are creating your Select2 from a input or a select.

Mine was created from a select so getting the data back from the AJAX call, I simply used the array containing the ID values of the selected items and passed it through like this

 $('#media_keywords').select2().select2('val', keywordArray)

keywordArray being the array of IDs.

Solution – 2

by jQuery in Multiple mode:

var selectedValues = ["1", "2"];
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.