I'm attempting to populate a combobox (input) with data fetched via AJAX. The goal is to display every city associated with a selected state, chosen from another select control (the state control).
My Attempt:
I've implemented the "change" event on the state comboBox, so that when a state is selected, I search for its cities and populate the city control.
$("#state").on("change", function () {
getCities($(this), $("#city"));
});
It's currently functioning as expected, but my main issue is that after bringing in the data to the control, I need to click on it to refresh it (the previous state data remains). Ideally, this should happen automatically once I finish selecting the state from the state select input. Another problem I'm encountering is that the first option "--- SELECT CITY ---" gets selected every time the state select input changes its cities. Below is the function code for reference:
function getCities(stateControl, cityControl) {
if (stateControl.val()) {
var options = '<option value="0" selected="selected">--- CHOOSE CITY --- </option>';
cityControl.html(options);
var dataString = "state="+stateControl.val();
$.ajax({
type: "POST",
url: "cities.php",
data: dataString,
dataType: "json",
success: function (response) {
for(var i=0; i < response.length; i++){
options += '<option value="' + response[i].cod_cidade + '">' + response[i].nome + '</option>';
};
cityControl.html(options);
}
});
}
}
}