I have a JSON array in a JSON file looks like this:
{
"states": [
{
"state": "Andhra Pradesh",
"districts": [
"Anantapur",
"Chittoor",
"East Godavari",
"Guntur",
"Krishna",
"Kurnool",
"Nellore",
"Prakasam",
"Srikakulam",
"Visakhapatnam",
"Vizianagaram",
"West Godavari",
"YSR Kadapa"]
}
]
}
and I am successfully able to load all states in the select element as a dependent select option . when I select a state from a select element it populates a related array in the district select element. but instead of the array showing a separate option it shows as one option:
Should I modify my JSON array in a different format?
jquery
$('#statePicker').on('change', function() {
$("#cityPicker").html('');
$.ajax({
url: "{{ asset('json/in-sc-list.json') }}",
type: "GET",
dataType: 'json',
success: function(res) {
$('#cityPicker').html('<option value="">Select City</option>');
$.each(res.states, function(key, value) {
if (value.state == $('#statePicker').val()) {
console.log(value.districts);
$("#cityPicker").append('<option value="' value
.districts '">' value.districts '</option>');
}
});
}
});
});
blade
<span>
<select id="statePicker" name="statePicker" required ></select>
<select id="cityPicker" name="cityPicker" required ></select>
</span>
CodePudding user response:
let statePicker = $('#statePicker').val();
let list = $("#cityPicker");
$.each(res.states, function(key, value) {
if (value.state == statePicker) {
$.each(items, function(item) {
list.append(new Option(item, item));
});
}
});
You need to loop value.districts
because its an array, and also, you are doing it in a dirty way, you are initializing $("#cityPicker")
on every loop, This might give some performance issues in future if the list items increases.
CodePudding user response:
Your data structure is fine. The issue is that you're not creating multiple option elements, you're only creating one. This part is off:
$("#cityPicker").append('<option value="' value
.districts '">' value.districts '</option>');
}
What you want to do is create an option element for each district, as follows:
for (const district of value.districts) {
$("#cityPicker").append('<option value="' district '">' district '</option>');
}