3
votes

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.

1

1 Answers

1
votes

First thing you can dynamically append options using the data attribute even for a multi dimensional json array of objects. But do not initialize the select box twice!

$("#country").select2({ data: data.keys });

Instead destroy it and init with your values, you can also try with change event.

$("#country").select2('destroy').empty().select2({ data: data.keys });

Let me know if this helps.