I have a select field $("#country") in a ACF form on Wordpress backend which triggers the values for a second select field $("#city"). It's a typical Country/City relationship with custom values.
The script is enqueued, the change event is triggered and the second select gets populated with success using this code:
var cities = {
"Spain": [
"Madrid",
"Barcelona"
],
"Portugal": [
"Lisboa",
"Oporto"
]
}
jQuery(document).ready(function($) {
$('#country').change(function () {
loadCities($(this).find("option:selected").val());
}).change();
});
function loadCities(country) {
$('#city').empty();
cities[country].forEach(function(city) {
$('#city').append("<option value='"+city+"'>"+city+"</option>");
});
}
As the list of cities is quite long, I want to use select2 instead of select. Here the changed loadCities function:
function loadCities(country) {
$('#city').empty();
var data = [{id: "", text: ""}];
cities[country].forEach(function(city) {
data.push({id: city, text: city});
});
$('#city').select2({
data: data,
placeholder: "Select a city"
}).trigger('change');
}
The problem is that the options (=cities) don't show up as expected in the select2 list. But they seem to be appended, checking their existence with jquery shows them.