I have a CodePen that loads cities
after a country
is selected..., now with //$("#country").val("3");
code commented the "manual" change of the coutry works well.
But the "automatic" (code uncommented) load of the country
does not change the cities... why?
PS. I don't want to trigger "change" event manually. for me is strange I should do it by hand...
document.addEventListener("DOMContentLoaded", function(event) {
var countries = {
"1": ["Paris", "Lyon"],
"2": ["Berlin", "Cologne"],
"3": ["London", "Edinburgh"]
};
function loadCities(countryId) {
var cities = countries[countryId];
var container = "#city";
$(container).empty();
$(container).append($("<option/>", { value: 0, text: "select a city..." }));
$.each(cities, function(key, city) {
$(container).append($("<option/>", { text: city }));
});
}
$("#country").on("change", function() {
var countryId = $(this).val();
loadCities(countryId);
});
$("#country").val("3");//.trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="country">
<option value="0">select a country</option>
<option value="1">France</option>
<option value="2">Germany</option>
<option value="3">UK</option>
</select>
<select id="city">
<option value="0">no country selected</option>
</select>