Here is my code:
$(function () {
var region = $('#region');
var city = $('#city');
var pickedRegionId = region.find(':selected').val();
var options;
if (pickedRegionId === '') {
console.log('region is empty, html() and disable');
city.html('');
city.attr('disabled', true);
}
region.change(function(){
console.log('region is changed');
pickedRegionId = $(this).val();
if (pickedRegionId !== '') {
city.html('');
console.log('loading cities');
getCities(pickedRegionId);
}
});
function getCities (regionId) {
city.attr('disabled', true);
city.html('<option>Loading...</option>');
$.get(
'/ajax/get_cities',
'region_id='+regionId,
function (responce) {
if (responce.result === 'success') {
$(responce.cities).each(function(){
options += '<option value="'+$(this).attr('id')+'">'+$(this).attr('city')+'</option>';
});
city.html(options);
city.attr('disabled', false);
}
}, 'json'
);
}
});
When page loads all is ok, I pick some region and select with cities fills with ajax data.
But when I pick another region, data in cities select just extends with newer data.
So the problem that I have cities from both regions(new and old one). And not matter how many times I pick another region it’s just adding new data to city select. In the code all looks fine and on region change I’ve put .html(”) so it should be empty before inserting received values. But I can’t figure out what the bug is.
You are just appending to options and not clearing it at all. I would empty your options just below where you set
citiesto loading.