I'm currently working on a script that dynamically populates the state dropdown menu based on the selected country id. Everything seems to be functioning correctly, but I've encountered an issue where I can only save the country selection using html localStorage upon page reload, and not the state option.
Below is the code snippet in question:
$(document).ready(function() {
var country_id = null;
var state_id = null;
$('#country').select2();
$('#state').select2();
$('#city').select2();
$('select[name="country"]').on('change', function() {
var country_id = $(this).val();
if (country_id) {
$.ajax({
url: "/world/getStates.php",
type: "GET",
data: {
'country_id': country_id
},
dataType: "json",
success: function(data) {
$('select[name="state"]').empty();
$('select[name="city"]').empty();
$('select[name="state"]').append('<option value="">Select State</option>');
$.each(JSON.parse(data), function(key, value) {
$('select[name="state"]').append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
} else {
$('select[name="state"]').empty();
}
});
// More code for handling state selection...
$('#country').val("value from localStorage").trigger('change');
$('#state').val("value from localStorage").trigger('change');
});
// Additional styling and scripts here...
After implementing this logic, I noticed that the country selection is successfully retrieved from localStorage and triggers the change event, but the same process does not apply to the state selection. Any insights on what might be causing this discrepancy?