Seeking a more efficient way to load data from a JSON file based on the user-selected option. Currently, I am using multiple else if statements for each state, but it feels repetitive and cumbersome. Is there a better approach? Here's a snippet of my code:
Example:
<select id='test-select'>
<option>AL</option>
<option>AK</option>
<option>AZ</option>
</select>
Script:
var cities = [];
$.getJSON('/assets/shared/misc/counties.json', function(json) {
// pushing json to cities array
cities.push(json);
// looping through each item
$('.state-names').map(function(index) {
// loading json data based on select option
$('#test-select').on('change', function() {
var target = $('#test-select option:selected').val();
console.log(target);
if (target == 'AL') {
$('.state-names').text(cities[0].AL);
} else if (target == 'AK') {
$('.state-names').text(cities[0].AK);
} else if (target == 'AZ') {
$('.state-names').text(cities[0].AZ);
} else if (target == 'AR') {
$('.state-names').text(cities[0].AR);
} // end else if block
}); // end test select function
}); // end map function
console.log(cities);
}); // end getJSON call
This is just a small portion of the code, but it involves many more options and else if's. Is there a way to simplify this process without repeating so much code? Any assistance is appreciated. If additional details are needed, feel free to ask. Thank you.