I am dynamically populating two select dropdowns with data from two separate arrays

After setting up the first select list, the task at hand is to generate elements for each item in the "selectList.chains" array. Each element must consist of a label text node and a 'value' attribute before being appended to another element. This will allow the second option list to populate with sizes corresponding to the selected chain. A new size array has been created to facilitate this process.

//HTML

<div id="selects">
  <div id="select1Div" style="float:left;margin-right:15px;"> Select
              Your &lt;Chain&gt; 
   <br>

   <select name="firstSelect" id="firstSelect">
       <option>----</option>
   </select>
</div>

<div id="select2Div"> Select Your &lt;Chain Length&gt;<br>
    <select name="secondSelect" id="secondSelect">
        <option>----</option>&nbsp;
    </select>
</div>




//JavaScript
    var sel1 = document.getElementById("firstSelect");
     var sel2 = document.getElementById("secondSelect");

     var selectList = {
         "chains": ["rice", "snake", "omega", "neoprene"]
     }

     var size = new Array()
     size["empty"] = ["Select a Length"]; 
     size["rice"] = ["16inch", "18inch", "20inch", "22inch"]; 
     size["snake"] = ["16inch", "18inch", "20inch", "22inch"]; 
     size["omega"] = ["16inch", "18inch"]; 
     size["neoprene"]= ["16inch", "18inch", "20inch"]; 

     for (var i = 0; i < selectList.chains.length; i++) {
         //create <option>
         var s = document.createElement("option");
         //create text node
         var t = document.createTextNode(selectList.chains[i]);
         // add text node to <option>
         s.appendChild(t);
         // set value="" on the <option>
         s.setAttribute("value", selectList.chains[i]);
         // add the new <option> to the <select>
         sel1.appendChild(s);
     }
    // This section will react to user selections on our drop-down list
    // and write to the page
      sel1.addEventListener("change", function(e) {
         //get the selected value from "chains"     
         var val = this.value;
          console.log(this.value);
         var s = document.createElement("option");
     // use the selected option value to retrieve the list of items from the size array 

Answer №1

Check out this link for more information

Recently included in the code:

 sel2.innerHTML = "";
          for (var i = 0; i < size[this.value].length; i++) {
         //create <option>
         var s = document.createElement("option");
         //create text node
         var t = document.createTextNode(size[this.value][i]);
         // add text node to <option>
         s.appendChild(t);
         // set value="" on the <option>
         s.setAttribute("value", selectList.chains[i]);
         // add the new <option> to the <select>
         sel2.appendChild(s);
     }

This change listener function will clear the current content of sel2 and replace it with the updated elements.

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

Guide on transforming json into a string using php

I am looking to convert JSON data into a String using PHP. Below is the JSON data that I have: { "": [{ "description": "hello, this is description speaking" }, { "fieldName": "myfile", "originalFilen ...

Create a customized menu with jQuery that disappears when hovered over

Check out this menu I've created: http://jsbin.com/useqa4/3 The hover effect seems to be working fine, but I'm looking to hide the div #submenuSolutions when the user's cursor is not on the "Solution" item or the submenu. Is there a way to ...

How can I arrange my dates in the format mm/dd/yyyy?

Currently, the format I am receiving from my localhost is 1990-01-01T16:00:00.000Z. What I actually want is the format to be 01/01/1990 and to be able to easily set it in my form. Here is my JavaScript code... var vm; vm = this; vm.data = {}; ...

Even when it appears to be chaotic, the TypeScript array of numbers always manages to find its way back to being sorted

I recently developed a function that aims to verify if an array of numbers is sorted: const checkIfSorted = (numbers: number[]) => { return numbers === numbers.sort((a, b) => a - b); }; checkIfSorted([4, 2, 8, 7, 3, 10, 1, 5, 9, 6]); // This cur ...

Strategies for effectively searching and filtering nested arrays

I'm facing a challenge with filtering an array of objects based on a nested property and a search term. Here is a sample array: let items = [ { category: 15, label: "Components", value: "a614741f-7d4b-4b33-91b7-89a0ef96a0 ...

When refreshed, CSS and JavaScript were not loaded

As a newcomer to AngularJs, I am facing an issue that has left me puzzled. I am attempting to create a single-page application using AngularJS + ExpressJS. Everything is functioning properly, but I am encountering a problem upon page refresh. For example, ...

Why is the wrong value being echoed in this code snippet?

Why is the code echoing an incorrect value? When data is entered into the input field like this it will output 111 8 333 444 8 666 777 8 999 Why is it not echoing 111 222 333 444 555 666 777 888 999 What can be done to resolve this issue? .......... ...

Reading a Json file with keys in puppeteer BDD: A Guide

Greetings, I am new to the world of puppeteer. I have successfully created my basic framework and now I am trying to figure out how to read data from .json files. I attempted to use the readFile method in my helper class, but unfortunately, it resulted in ...

Out of nowhere, my React App has decided to stop working despite no recent changes

Hi everyone, I recently forked a React app from https://github.com/conedex/frontend. It was working perfectly fine until it suddenly stopped with this error message: ./node_modules/@metamask/utils/node_modules/superstruct/dist/index.mjs 46:43 Module parse ...

Error encountered: Cannot access the method 'tapAsync' from an undefined object in file ExternalModuleFactoryPlugin.js at line

While working on my React project, I decided to set up Storybook. However, I encountered an error that is preventing me from running my Storybook (5.3.7) with webpack-5-beta-14. /node_modules/webpack/lib/ExternalModuleFactoryPlugin.js:30 normalModuleFact ...

Modifying the app.css file in the source tab of dev tools does not cause any changes in the DOM when working with a

Just starting out with react js here. While exploring developer tools in Chrome, I attempted to tweak some CSS in the elements panel and noticed the changes reflecting above in the DOM. However, when I navigate to the sources tab, I'm unable to modify ...

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

Escape key does not close the modal dialogue box

I’ve customized the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on a webpage. Although it functions as intended, I’m struggling to implement a way to close it by pressing the escape ...

The PDFKIT feature ensures that any overflowing data in a row is automatically moved to a new page

A function in my code generates a row of data based on an array. It works perfectly fine for the first page, but as soon as the data overflows somewhere around doc.text("example",70,560), it jumps to the next page. The issue arises when the Y coo ...

What is the significance of the @brief tag in an Angular 6 application?

Recently, as I was working on my Angular 6 project, I came across some hashed comments that looked like this: /** @brief the displayed list of vehicles */ and this: /** @brief dummy database of vehicles */ I couldn't help but notice that '@br ...

Having issues with $emitting not working for parent-child components in Vue. Any ideas on what I might be doing incorrectly?

I have a login component that I need to call in the main vue component of App.vue. Within the login vue, when I click on any button, it should activate another vue component using Vue.js router to replace the login page. I have searched for solutions but h ...

Detecting Scroll on Window for Specific Element using Jquery

I need help troubleshooting my code. I am trying to activate only one item that comes from the bottom of the page, but instead all div elements are getting activated. $(window).scroll(function() { $('.parallax').each(function(e) { if($( ...

I'm interested in learning more about how to select or deselect all checkboxes

How can I uncheck the "all" checkbox when I uncheck another checkbox? $('#All').click(function () { var status = $(this).is(":checked"); if (status) { $.each($('input[name="checkbox"]'), function () { this. ...

What is the location of the files stored using the cordova-file-plugin?

Currently, I am in the process of developing an Excel application on a mobile device. Initially, I'm testing it out on Android, but the aim is to ensure compatibility with iOS devices as well. To build this app, I referred to the official documentati ...

Angular Automatically Generated Identifier for Event Detection

By using jQuery, I can easily target an ID that starts with "conditionValue" $(document).on('focus', "[id^=conditionValue]", function (event) { // code }); But how can I achieve the same in Angular when looking for an ID starting with somet ...