Select2: loading selected values

2020-06-28 03:26发布

问题:

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.

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

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"}];

                $('#media_keywords').select2({
                    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.

回答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.