0

I'm trying to make an edit form. This form must load data that comes from a database and show the data as it comes from it. In my form, I have a select2 combo-box that loads the items via ajax. I need to change the selected index of this combo box using the id value that comes from the database. The code that I use to load the data is:

function populateState(){


var urlCities='@routes.StateCtrl.lstStatesByCountryToSelect()';
$("#idCountry").select2({
    placeholder: "Select country...",
    ajax: {
    url: urlCities,
    dataType: 'json',
    type: 'GET',
        data: function(term,page){
                return{q:term,idCountry:$("#idCountry").val()};
                },
        results: function(data, page) {
            return {
                results: data.results
            };
        }
    }
});

}

I was trying with this but it did not work:

$("#idCountry").select2().select2("val", id);

For example if I load three states in the combo box (Texas, New York, Florida) when the page loads, I want to show in the combo box Texas as the initial selected item.

  • The approach to Select2 ajax was completly changed in 4.0 version. You need to use data-adapters to get it work. Hopefully this helps : http://stackoverflow.com/questions/33949508/prevent-reload-of-data-with-select2-plugin-v4/34079165#34079165 – DinoMyte Feb 26 '16 at 20:12
  • Possible duplicate of [Select2 4.0.0 initial value with Ajax](http://stackoverflow.com/questions/30316586/select2-4-0-0-initial-value-with-ajax) – Kevin Brown-Silva Mar 01 '16 at 15:39
  • I solved the problem downgrading to version 3.5.2. – Víctor Minero Mar 04 '16 at 21:15

1 Answers1

0

$("#idCountry").val("desired_value").trigger("change");

More can be found here under Deprecated and removed methods: https://select2.org/upgrading/migrating-from-35

myles
  • 18
  • 6