This week has been quite challenging as I attempt to filter a JSON file based on the ID retrieved from a dynamically generated dropdown list.
- CSS Framework: Bootstrap;
- JS Framework: Jquery and Bootstrap Js
I am striving to achieve this without relying on Jquery or Bootstrap Js. My aim is to utilize Vanilla Js instead.
To begin:
I programmatically created a dropdown list populated with data from a JSON file, assigning a unique ID to each element.
// FETCH DROPDOWN LIST FROM JSON FILE
fetch('dropdown.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
let output = '';
data.forEach(function (data) {
output += `
<a class="dropdown-item" href="#" id="${data.id}">${data.text}</a>
`;
});
document.getElementById('div-dropdown-list').innerHTML = output;
});
Next, I need to display information from other JSON files based on the selected ID. To achieve this, I'm accessing the ID of the previous dropdown list using an Event Listener:
document.querySelector('#div').addEventListener('click', async (e) => {
const idSelected = await e.target.id;
});
Following that, I am directing my attention towards the JSON file containing the desired data filtered by the obtained ID.
async function json() {
const response = await fetch('data.json');
const data = await response.json();
return data;
}
json().then(info => console.log(info));
How can I display the JSON data filtered by the idSelected variable within the document.querySelector('#div').addEventListener?