Develop a pair of linked drop-down menus using JSON information

I am currently developing a feature that involves creating two dependent lists using values extracted from a JSON variable.

The data is structured like this:

{
      "Name1": [
        {
          "Name1_Nickname": "ID1"
        }
      ],
      "Name2": [
        {
          "Name2_Nickaname": "ID2"
        }
      ],
      "Name3": [
        {
          "Name3_Nickname1": "ID3_1"
        }, {
          "Name3_Nickname2": "ID3_2"
        }
      ]
    }

Currently, I am working with a

Map<String,List<Map<String,String>>>
which I parsed into a JSON object. My goal is to create a primary Picklist containing all the options such as Name1, Name2, and Name3, then based on the selection of a certain Name, generate a secondary picklist displaying corresponding nicknames like Name1_Nickname for Name1 or Name3_Nickname1, Name3_Nickname2 for Name3.

Answer №1

One way to dynamically populate select options based on an object is by looping through the object properties. Additionally, you'll need to create an event listener for when the first select option changes.

var items = {
      "Name1": [
        {
          "Name1_Nickname": "ID1"
        }
      ],
      "Name2": [
        {
          "Name2_Nickaname": "ID2"
        }
      ],
      "Name3": [
        {
          "Name3_Nickname1": "ID3_1"
        }, {
          "Name3_Nickname2": "ID3_2"
        }
      ]
    };

var one = document.getElementById("one");
var two = document.getElementById("two");

// Loop through object properties to populate the first select
for(var prop in items) {
  var option = new Option(prop, prop);
  one.appendChild(option);
}

// Add event listener for the first select change
one.addEventListener("change", function(e) {
  var value = e.target.value;
  
  // Clear the second select options
  for(var i = two.options.length; i > 0; i--) {
    two.options[i - 1].remove();
  }
  
  // Populate the second select based on the selected item
  items[value].forEach(function(item) {
    for (var itemProp in item) {
      var option = new Option(itemProp, item[itemProp]);
      two.appendChild(option);
    }
  });
  
});

// Trigger a change event to set default options in the second dropdown
var changeEvent = new Event('change');
one.dispatchEvent(changeEvent);
<select id="one"></select>
<select id="two"></select>

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

Secure your API routes in NextJS by using Passport: req.user is not defined

Currently, I am utilizing NextJS for server-side rendering and looking to secure certain "admin" pages where CRUD operations on my DB can be performed. After successfully implementing authentication on my website using passport and next-connect based on a ...

"Trouble encountered when submitting data to an external system by writing the image source - issues with Firefox and

I've been diving deep into various online resources to find a solution for an issue I'm encountering. My familiarity with Javascript is limited, so please bear with me. Whenever I click on the next button during checkout, a script runs to submit ...

What's the best way to create flying text effects - using CSS or JavaScript

Looking for a way to enhance the user experience of my shopping cart on Android and iPhone/iPod, I want to implement a feature similar to the iTunes Store where the price flies down to the total when a purchase is made. Since I use jQuery (not UI) on this ...

Tips for Resolving SyntaxError: Unexpected token = When Class Import is Done

After creating a class in a separate JavaScript file and importing it into another file, I encountered a syntax error within the exported class. All seemed fine when the class was not being exported. Here is the code for Property.js (the exported class): ...

Ensuring Form Security with JQuery Validation

Hello everyone, I'm currently working on a login form with jQuery validation to ensure that the user ID and password entered are valid. So far, this is what I have implemented: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/l ...

React-router-dom v6 causing MUI Drawer to not render

I have implemented ReactJS and I am working on incorporating a drawer/menu to display different routes on each page. I have set up the routes using react-router-dom@v6 in my index.js file. When I directly enter the URL for a specific page, I can see the co ...

The variable "payload" within the messaging.onMessage() function in AngularJS (version 1.6) is returning as undefined when using FCM

In my AngularJS app, I am using FCM (Firebase Cloud Messaging) to connect to Firebase and receive a messaging token. I am able to successfully retrieve the token and see messages in the console. >>firebaseDependencies: Object { app: {…}, appConfig ...

How does spring-web handle the serialization and deserialization of data objects into JSON during an HTTP request?

Spring/Springboot offers a robust framework for building web applications. One of its standout features is its seamless implementation of ReSTful HTTP calls. These calls can even handle data objects like the following: public class User { private long ...

Feeling lost when it comes to updating CRUD operations following the integration with mlab

I have developed a basic CRUD app that successfully loads blog posts from my local mongo database and renders them to an html page. However, when I attempted to load api data from mlab, I encountered issues with DELETE, PUT, and POST operations. While the ...

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...

Displaying an overlay using jQuery's .fadeIn() method after switching to another browser tab

I created a script that displays numbers on a background with a fading in and out effect, similar to a matrix theme. Everything was running smoothly until I switched to a different browser tab. Upon returning to the tab with my script, the fading numbers ...

Is there a Node.js method that is similar to jQuery AJAX's .complete() function

In the process of creating a Node.js API to enroll a user in a different web application, I encountered an issue. As part of the registration flow, the API called by the Node app using request is being redirected with a status code of 301 to another API to ...

Encountered an error while running npm run dev on a NextJS application due to an

Upon running the npm run dev command, the next app is displaying an error message: $→mmoLD;%g?wŷ↓▬ovH0a5*ؒl͛Siy☺rO7%L]%∟hk ^ SyntaxError: Invalid or unexpected token at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._comp ...

Tips on how to choose all elements that do not include a specific value or group of values in cypress

Here's my situation: selector: ".list > div" const velue = [6, 9, 21] Each div contains a different value. I want to remove elements that contain a specific value, then select the first remaining element and click on it. It should look ...

The HTML button failed to toggle on in Div's previous attempt

Check out this JSFiddle link I'm trying to hide a div when the page loads and then show it when a button is clicked, but for some reason it's not working properly. Any suggestions on how to fix this issue? Here's the HTML code I'm usi ...

Error encountered while trying to send an array list using the $.ajax function in jQuery

My web API expects JSON data in the following format (input parameter) { "districtID": "string", "legendIDs": ["string","string"] } Below is the JavaScript code I am using to build the request: var cityDistrictId = 'fb7b7ecd-f8df-4591-89de-0c9d ...

Having trouble with a JQuery selector not functioning properly when trying to select a class in the HTML that contains a

Looking for help with a JQuery selector to target the title of a YouTube video. Here's the HTML snippet: <div class="ytp-title-text"> <a class="ytp-title-link yt-uix-sessionlink" tabindex="13" target="_blank" ...

Retrieve the subdomain from within the passport FacebookTokenStrategy and GoogleStrategy

In the process of developing a node.js application with wildcard subdomains, I am creating separate parts of the app for each subdomain that will have distinct user authentication based on the subdomain. For instance, envisioning my app having subdomains ...

Stop the change event from occurring on a textarea when the user clicks on an external cancel button

In a particular scenario, there is a textarea with an autosave feature triggered by the change event. When the textarea is focused on, Save and Cancel buttons appear at the bottom, providing users with options in case they prefer not to simply click outsid ...

Extract JSON information from a given URL and showcase it in a tabular format on a display

The information is structured in the following format at the specified URL { "studentsinfo": [ { "id": "100", "name": "Adam", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91f ...