Filtering a JSON file in JavaScript based on the selected id from a dropdown list

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?

Answer №1

I was able to successfully complete the task using the following code snippet

let select = document.getElementById('Select');
let dropdown = '';

const displayOptions = import('../metadata/dropdown.json').then(
  (module) => {
    const data = module.default;
    data.forEach((data) => {
      dropdown += `<option value="${data.id}">${data.value}</option>`;
    });
    div.innerHTML = dropdown;
  }
);

module.exports = displayOptions;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending a multi-dimensional array to the server using PHP via POST

Similar Question: multi-dimensional array post from form I am looking to transfer data from the client to the PHP server using jQuery's $.post() method. Once the data reaches the server, I want the $_POST['myList'] variable to be in one ...

What causes a "UnhandledPromiseRejectionWarning" while using Puppeteer?

What causes the following warnings to appear, and how can I resolve them? Warnings: (node:26771) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Protocol error (Runtime.callFunctionOn): Target closed. (node:26771) ...

Utilizing PHP to Work with Nested JSON Objects

I am attempting to gather these outcomes in PHP arrays for the purpose of encoding them into JSON objects. My goal is for the JSON objects to have this structure: {"ShopApp":[{"cid":"31","category_name":"Category 1","category_image":"99520_category1.png" ...

Guide to running a Vue 3/Vite application in library mode for testing or demonstration needs

Currently, I am in the process of developing a Vue 3 components library and transforming it into an npm package using Vite.js. Following the guidelines provided in the official documentation, I have successfully configured Vite. However, I am faced with th ...

Developing personalized Jackson deserializer for external SDK

I am currently working on creating custom Jackson deserializers for classes within a third-party library. I have successfully created one for a basic class (Duration), but I am now facing the challenge of creating one for another class (RetryPolicy) that c ...

What is the best way to determine the nearest vertex to a given 3D point?

https://i.sstatic.net/Ooh8W.png Objective: I am aiming to identify the closest vertex to the clicked point. Components Needed: Perspective camera Icosahedron geometry (applied basicmeshmaterial with wireframe) Rotating geometry Raycaster Current Clic ...

Updating className in React by responding to button clicks without relying on numerous conditional statements

I've been working on a small project for the past few weeks. The main idea is to have a stepper with different steps that the user can click on to see their tasks for each step. There is also a completion button for each step, but I'm struggling ...

After successfully logging into Google, I am interested in synchronizing Google Calendar events using JavaScript

I have implemented code to authenticate users and synchronize Google Calendar events directly. const handleClick = () => { gapi.load('client:auth2', () => { console.log('loaded client') gapi.cl ...

Troubleshooting issue with Django development server causing HTML5 video element to become non-seekable

My Django app is currently serving a webpage with an HTML5 video element, but I've encountered a strange issue. The video.seekable property is returning a timeRanges object with a length=0, when it should actually be length=1. Unfortunately, this mea ...

Creating a dynamic slideshow with automated arrow navigation is simpler than you may think

I have successfully tested the slideshow and it is functioning perfectly without any issues. I would like to have a dual slideshow setup (slideshow 1 and slideshow 2) with next and previous buttons, but I am interested in adding an automatic sliding featur ...

Expo-three is experiencing an issue with its lights not functioning properly in threejs

Seeking assistance: I recently discovered the compatibility of the ThreeJS library with react-native, which is truly remarkable! After conducting a small experiment, I encountered some issues with the lighting. Unfortunately, I am unable to modify the ligh ...

Sequential timeouts overlap when updating an element's text multiple times using jQuery, causing rapid jumps between intermediate states

I am attempting to change an element's text gradually with a 1-second interval between each change. The issue I'm facing is that it skips the in-between changes and directly jumps from the initial text of the element to the final text ('tex ...

Utilize the qtip function in a loop using the .each method

I'm encountering an issue with implementing the Qtip jQuery plugin across a whole class of HTML elements: $(".peoplebtn").each(function() { $(this).qtip({ content: { text: $(this).attr('qTipText') } }); }); ...

Tips for continuing a count from where it left off

I have encountered an issue with the input fields in my form. I used the counter method to add input fields and saved the form. However, when I try to add more fields, the counter starts from 0 again. For example, I initially added 5 input fields with mod ...

The JavaScript application in Hyperledger Fabric's node app.js isn't functioning properly

As a newcomer to the blockchain industry, I decided to delve into Hyperledger by following the instructions provided in this documentation. After downloading all the necessary prerequisites and setting everything up correctly, I successfully executed the n ...

Creating an HTML return statement to specifically target and extract a certain string while disregarding additional data

Looking for a solution to trim a long string returned by a webpage, while ensuring essential data is not removed. Counting characters is not feasible due to the varying length of the return. The return format is as follows: GET /New%20Messenger&subti ...

Choosing a root element in a hierarchy without affecting the chosen style of a child

I am working on a MUI TreeView component that includes Categories as parents and Articles as children. Whenever I select a child item, it gets styled with a "selected" status. However, when I click on a parent item, the previously selected child loses its ...

What is the best way to extract hover-box information from an ajax website with Python?

Attempting to extract the dimensions for each cell on a map from this AJAX site, where details only appear when hovering over the cells has proven unsuccessful so far. Using Python selenium webdriver and phantomJS did not yield any data when trying to loa ...

Looking to implement a delay in the model popup using Pure JavaScript

Looking for a method to implement a delay in the popup... I've tried a few solutions without success. What's the secret to adding a delay to the modal below? Any help is greatly appreciated. var modal = document.querySelector(".modal"); var t ...

Guide to retrieving a JSON object from an Azure Function using Node.js

When utilizing Azure Functions, how can you successfully return a JSON object in the response body from a node.js function? While it's straightforward to return a string, I encountered difficulties when attempting to return a JSON object as demonstrat ...