I have a json data which looks like this:
[{
"id": 9,
"category": "Baby",
"items": "[{\"value\":\"Baby Foods\"}]",
"created_at": "2022-01-08T14:28:48.000000Z",
"updated_at": "2022-01-08T14:28:48.000000Z",
"deleted_at": null
},
{
"id": 10,
"category": "Adult",
"items": "[{\"value\":\"Adult Clothes\"},{\"value\":\"Adult Bags\"},{\"value\":\"Adult Shoes\"}]",
"created_at": "2022-01-09T10:46:34.000000Z",
"updated_at": "2022-01-09T10:46:34.000000Z",
"deleted_at": null
}]
It has a list of categories with its items. Now what I am trying to do now is to populate that data on select boxes in a way that if a user change category queried from JSON will show items (as shown on JSON) to another select box as options belonging to that category selected.
Here is what I have tried so far using jquery:
let dropdown = $('#category');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose</option>');
dropdown.prop('selectedIndex', 0);
const url = 'http://localhost:8000/admin/categories/show';
// Populate dropdown with list of categories
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.category).text(entry.category));
})
});
Here is the result which shows categories on category select box perfectly:
I don't have idea how to get items if certain category is selected on another select box (second one) any help will greatly appreciated.
CodePudding user response:
You can define an eventHandler for your category change event, and whenver it changes, you can read related items from the source data, and put items in the target option, like this:
let data = [{
"category": "Baby",
"items": "[{\"value\":\"Baby Foods\"}]",
},
{
"category": "Adult",
"items": "[{\"value\":\"Adult Clothes\"},{\"value\":\"Adult Bags\"},{\"value\":\"Adult Shoes\"}]",
}
]
let categories = $('#category');
let items = $('#items')
function fillDropdown(target, {data, prop}) {
$.each(data, function(key, data) {
target.append($('<option></option>').attr('value', data[prop]).text(data[prop]));
})
}
fillDropdown(categories, {data, prop: 'category'})
categories.on('change', function(e) {
items.html('');
let value = $(this).val();
if (value) {
let dataItem = data.find(v => v.category == value);
const options = JSON.parse(dataItem.items);
fillDropdown(items, {data: options, prop: 'value'})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="category">
<option></option>
</select>
<select id="items"></select>

