"Incorporating JSON and Ajax to dynamically populate one select based on the selection in another select

I need to display data from a JSON file in select options, and here is the structure of my JSON file:

[{
    "vehicle": "car1",
    "type": [
      {"name" : "BMW",
      "details" : [{
        "color" : "red",
        "price" : "50000"
        },
        {
          "color" : "blue",
          "price" : "51000"
          }]}
    ]},
  {
    "vehicle": "car2",
    "type": [
      {"name" : "Lambo",
      "details" : [{
        "color" : "green",
        "price" : "150000"
        },
        {
          "color" : "yellow",
          "price" : "151000"
          }]}
    ]}
]

In order to populate values into two select elements, I implemented a loop in my code:

for (i = 0; i < data.length; i++) {
  select1.insertAdjacentHTML('beforeend', `
    <option>${data[i].vehicle}</option>
  `)

  for (j = 0; j < data[i].type.length; j++) {
  
    for (k = 0; k < data[i].type[j].details.length; k++) {
  
      select2.insertAdjacentHTML('beforeend', `
        <option">${data[j].type[j].details[k].color}</option>
      `)
    }
  }

This should create the following selection options:

  • Car1
  • Car2

And for the second select element:

  • Red / Green
  • Blue / Yellow

Based on the first selection option. However, there seems to be an issue with duplicate entries in the second select, as it's showing 4 items instead of just 2.

If anyone can assist me with this problem, I would greatly appreciate it. Thank you!

 var json_obj =  [{
        "vehicle": "car1",
        "type": [
          {"name" : "BMW",
          "details" : [{
            "color" : "red",
            "price" : "50000"
            },
            {
              "color" : "blue",
              "price" : "51000"
              }]}
        ]},
      {
        "vehicle": "car2",
        "type": [
          {"name" : "Lambo",
          "details" : [{
            "color" : "green",
            "price" : "150000"
            },
            {
              "color" : "yellow",
              "price" : "151000"
              }]}
        ]}
    ];


function apply_change(data) {
    var select1 = document.getElementById('select1');
    var select2 = document.getElementById('select2');

    for (i = 0; i < data.length; i++) {
      select1.insertAdjacentHTML('beforeend', `
        <option>${data[i].vehicle}</option>
      `)
    
      for (j = 0; j < data[i].type.length; j++) {
      
        for (k = 0; k < data[i].type[j].details.length; k++) {
      
          select2.insertAdjacentHTML('beforeend', `
            <option">${data[j].type[j].details[k].color}</option>
          `)
        }
      }

  }
}

apply_change(json_obj);
select 1: <select id="select1"></select>
select 2: <select id="select2"></select>

Answer №1

Adjusted the code to generate the desired output. Feel free to review my solution on jsfiddle. Select onchange - pure javascript

 var json_obj =  [{
        "vehicle": "car1",
        "type": [
          {"name" : "BMW",
          "details" : [{
            "color" : "red",
            "price" : "50000"
            },
            {
              "color" : "blue",
              "price" : "51000"
              }]}
        ]},
      {
        "vehicle": "car2",
        "type": [
          {"name" : "Lambo",
          "details" : [{
            "color" : "green",
            "price" : "150000"
            },
            {
              "color" : "yellow",
              "price" : "151000"
              }]}
        ]}
    ];


var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
LoadSelect1();

function LoadSelect1() {
  for (i = 0; i < json_obj.length; i++) {
     select1.options.add(new Option(json_obj[i].vehicle, json_obj[i].vehicle));
  }
  LoadSelect2(json_obj[0].vehicle);
}

function LoadSelect2(selectedvalue) {
  console.log(selectedvalue);
  select2.options.length = 0;
  for (i = 0; i < json_obj.length; i++) {
    if (json_obj[i].vehicle == selectedvalue) {
      for (j = 0; j < json_obj[i].type.length; j++) {
        for (k = 0; k < json_obj[i].type[j].details.length; k++) {
          select2.options.add(new Option(json_obj[i].type[j].details[k].color, json_obj[i].type[j].details[k].color));
          }
       }
    }
  }
 }
   select 1: <select id="select1" onchange="LoadSelect2(this.value)"></select>
   select 2: <select id="select2"></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

Adjusting editable property in FullCalendar during script execution

Currently, I am working with Angular JS and fullCalendar to customize the functionality of my calendar. My goal is to change the editable property of the calendar when a button is clicked. Although it seems like a straightforward task, I am facing difficul ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

What is the best way to push a variable after employing the split function in JavaScript?

error: An unexpected TypeError occurred while trying to read property 'push'. The error was on this line: " this.name[i].push(arrayData[0]); " I'm confused because the console.log statement before that line shows "data is loaded:" alo ...

What's the best way to enable touch scrolling for items within a div container?

I am in the process of creating a code snippet that will allow users to scroll through items within a div, similar to a spinning wheel or slot machine. While I am aware of an existing solution for iPhone and iPod, I want to develop a simpler, more streamli ...

Is it possible to conceal the source code within the dist js file using Vue JS?

I am looking to create a detailed logging page that showcases the logs without revealing the specific type of logging. I want to prevent users from accessing the minified vue JS script and easily reading the logged information. Is there a way to implemen ...

ExtJS web displays appear differently when viewed on Chrome's toggle device mode versus a mobile browser

Greetings, I have been working on developing a web application that can be accessed through a mobile browser. Initially, I created the web application and tested it in mobile mode using Chrome's simulation feature. However, when I tried accessing th ...

Unable to access style property, encountering error on separate page

Once again, I'm feeling a bit lost on where to go with this coding issue. It seems quite basic, but I'm struggling to pinpoint the problem. My goal is to hide several IDs, and while it does work, I keep encountering an error: Uncaught TypeError: ...

How can I make the droppable elements only drop within draggable elements in jQuery UI?

After reading several similar articles and questions, I am still struggling to get this working properly when there are multiple droppable elements with the same named class. Is there a way to ensure that the dragged element can only be dropped in a speci ...

Converting a date string from JSON into a time span: A step-by-step guide

I have a JSON response with a time value in the format of "sun dd/mm/yyyy - HH:mm" that I need to convert into a time span like "10 min ago, 2 days ago..." To do this, I created a method that converts the given date and time string into the format "X Hours ...

Encountering both a CORS error and data in Angular 7

My application is using Angular 7 for the front end and Node.js (express) for the backend. The cors module in the Node.js server.js file is implemented like this: var cors = require('cors') app.use(cors()); When making an API call from the fro ...

Dealing with API responses after submitting files in Angular

My current setup involves a form where users upload files to my node server. The server then performs some operations and responds with a JSON object. The POST request is not made through the controller, but by submitting the form directly. Once the serve ...

Creating a pattern for values ranging from 18 to 99, including leading zeros, using regular expressions

Looking for a Regular Expression that matches numbers from 018 to 099, inclusive. The numbers must range between 18 and 99, and include a leading zero for values less than 100. ...

Shifting elements between positions using jquery or angular

Here's the issue I'm facing... I have an array of movie divs (image and description) displayed using ng-repeat. Now, when I select one of them, I want to implement the following (almost like a game of positioning): 1) I want to smoothly remove t ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

NodeJS: Increasing memory consumption leads to system failure due to recursive scraping

Currently, I am utilizing a GET URL API in NodeJS to extract various data by looping through the months of the year across multiple cities. For each set of parameters such as startDate, endDate, and location, I invoke a scrapeChunk() function. This functio ...

Leveraging REST API for Ensuring Users in SharePoint 2013

I am currently working on automatically ensuring users via a REST API. Here is my REST call: $.ajax({ url: "blablabla/_api/web/ensureuser", type: "POST", data: "{ 'logonName': 'i%3A0%23.w%7Cdomain%09logonName' }", headers: { "X-Req ...

Access a three.js scene from a canvas element within the local environment to make alterations

Is it necessary to keep Three.js variables (scene, camera, renderer etc.) globally? I have devised a function that initializes canvas elements by taking a DOM position and other information to build the scene. This function is then passed to a render func ...

Is there a versatile Node.js HTTP request module that is compatible with both server-side and browser-side development, particularly when packaged with Webpack?

Currently, I am searching for a request module that can operate seamlessly in both the Node.js server and the client when compiled with Webpack. The requirements are quite straightforward. I simply need to execute some basic HTTP Ajax requests such as get ...

Shared variables in Node.js allow for multiple users to access different entry points simultaneously

In the process of transitioning my node-js application from a single-tenant database to a multi-tenant database, I am facing some challenges. The application code is accessed through an express api and various services are run through different entrypoints ...

Creating a filter using radio input in HTML and CSS is a simple and

Currently, I am delving into the world of Javascript and React, but I have hit a roadblock. My goal is to create a Pokedex, yet I am encountering some difficulties. I have implemented Radio Inputs to filter Pokemon by generation, but I am struggling with ...