I have a page with two Select2, one for the selection of countries, and the other for the selection of cities belonging to the countries of the first select. When I choose a country, then I type in the other select the first characters of the cities, and the Ajax call returns all the cities belonging to that country that have the name starting with the characters typed. This works when I open the page for the first time, but when I try to open the page to modify the data, the Ajax call in the cities select doesn’t start. This is my HTML with the two selects:
<div class="input-group selectNazioniCitta">
<select class="form-control select2" name="countr"></select>
<span class="input-group-addon"> - </span>
<select class="form-control select2" name="cities" multiple="multiple"></select>"
</div>
This is the js function where I initialize the Cities select and call the ajax function that returns the list of cities:
function updSelCitta(elem, country, city) {
var o = "url", sel = $(elem).find('select[name*="citiesNotValid"]');
cities = city.split(';');`
for (var i = 0; i < cities.length; i++) {
if (cities[i] == "") {
initialData.push({
id: "-1",
text: "Tutte"
});
selectedData.push("-1");
} else {
initialData.push({
id: cities[i],
text: cities[i]
});
options += "<option value=\"" + cities[i] + "\" selected>" + cities[i] + "</option>";
selectedData.push(cities[i]);
}
};
$(sel).val([]);
$(sel).append(options).trigger('change');
$(sel).select2({
language: "it",
placeholder: {
id: '-1',
text: 'Tutte'
},
width: '100%',
multiple: true,
allowClear: true,
ajax: {
delay: 500,
type: "POST",
contentType: "application/json; charset=utf-8",
url: o,
dataType: "json",
cache: 1,
data: function (params) {
var query = JSON.stringify({
country_code: country,
search: params.term
})
return query;
},
processResults: function (t) {
return {
results: $.map(JSON.parse(t.d), function (obj) {
if (obj.city_name == "-") {
return { id: "-1", text: "Tutte" };
}
return { id: obj.city_name, text: obj.city_name };
})
};
},
error: function (t, o, i) {
var n = "Error. Check parameters";
})) : console.log(n)
}
},
minimumInputLength: 2,
});
}