"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

Having trouble structuring URL data in JSON format? Look no further! Check out the example source URL provided for guidance

Check out the URL source code here: I attempted to use this code, but encountered an issue with struct integration. struct Weather: Codable { let weather : [cos] let base: String } struct cos : Codable { let main: String } ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Is there a way to manually add route resolve data to a controller without using automatic injection?

Two routes in my application share a controller, but one route requires data to be resolved before the view loads while the other does not. Here is an example of the routing segments: ... when('/users', { controller: 'UsersCtrl', ...

Creating dynamic attributes for hibernate mapping through front-end integration

Currently, I am facing the challenge of inserting JSON data into our database using a combination of Spring Boot, Hibernate, and Angular. The specific attribute name within this JSON data remains unknown during compile time. Is there a viable solution tha ...

Change the behavior of an onclick event on the second click

I'm trying to make a button on my website that not only plays music when clicked but also changes the text inside the button to "Go to SoundCloud" and redirects to SoundCloud. Currently, I have been able to achieve both functions separately - redirect ...

How can you effectively transfer arguments from one component to another using router.push() in Vue.js?

I need help with implementing a feature where upon clicking the edit button in a row, all the details from that particular row should be passed to a form component. I want to populate the form fields with default values from the parameters provided. Can ...

Pull in content or data from a separate page by leveraging AJAX

Hello, I'm just starting out in programming and I could really use some help with this issue. index.html <button id="press">Click here</button> <div id="show_image"> </div> <br> <div id="appended_area"></div&g ...

Steps to improve the appearance of the Header on a dataTable during Dragging

I am working on creating a table that can be reordered using mat-table and MatTableDataSource. However, I would like the column to have a white background color instead of being transparent when dragged. Is there a way to achieve this? <table mat-tab ...

POST access not permitted in REST service

After creating a REST service and successfully connecting to it using JQuery ajax with JSON data, I encountered an issue specifically when trying to use the POST method. For some reason, the service is not being triggered during a POST request. The error ...

Leverage Typescript to convert string literal types to uppercase

type x = 'first' | 'second' I am looking to create a type y that is similar to this: type y = 'FIRST' | 'SECOND' Here is what I attempted: type x = 'first' | 'second' type y = {[key in x]: key[& ...

Reactjs Expressjs data display issueI'm experiencing difficulty with displaying

When I try to access the data using "dataUtilizador.Roles[0].name" after receiving a response from axios, the page goes blank. However, if I import the axios response and use "Record.Roles[0].name", it works fine. What am I doing wrong? import Record from ...

Transmit information to PHP via JSON with Cross Domain communication

My code is server1 and PHP code is server2. These servers are not connected. What issues can arise from this setup? var req = new XMLHttpRequest(); req.open("POST", "http://www.example.com/form/data.php", true); req.setRequestHeader("Content-type", "ap ...

Unlock the power of JavaScript and jQuery by utilizing inner functions

Here's some JavaScript and jQuery code with an ajax request included. Can you solve the mystery of why success1() can be called, but not this.success2()? Any ideas on how to fix this issue? function myFunction() { this.url = "www.example.com/ajax ...

Display the div if the input field is left blank

Is there a way to display the div element with id="showDiv" only if the input field with id="textfield" is empty? <form action=""> <fieldset> <input type="text" id="textfield" value=""> </fieldset> </form> <div id="sh ...

Track and monitor data modifications in Vue.js

I recently incorporated a Bootstrap Vue Table into my application and wanted to monitor user activity as they navigate through the pages using the pagination feature. Here is where you can find more information on the Bootstrap Vue Table To achieve this, ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

Opt for a line break over a semicolon when using jQuery

I need assistance with breaking the line wherever a semicolon is present. var locdata = { "locations": [{ "id": 0, "name": 'USA', "cx": 100, "cy": 100, "address":'545, 8t ...

How to use jQuery to iterate over changing elements and retrieve their data values

Exploring the potential of a collapsible panel to meet my requirements $(".sport").on("click", function() { var thisId = $(this).attr("id"); var thisChildren = $(this) + ".sportlist"; $(thisChildren).each(function(index) { }); }); <link ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

Troubleshooting npm audit error involving loadVirtual and ENOLOCK

➜ npm safety check npm ERR! code ENOLOCK npm ERR! safety check This operation requires an existing lockfile. npm ERR! safety check Please generate one using: npm i --package-lock-only npm ERR! safety check Original error: loadVirtual needs a preexistin ...