I want to create a file that has two dropdown menus, where the second dropdown options are dependent on the selection from the first dropdown. I have never written HTML before and I don't really now what I'm doing, so apologies in advance. I have tried to repurpose the code from https://www.w3schools.com/howto/howto_js_cascading_dropdown.asp for three dropdowns. Below, I provide my attempt to repurpose 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() { //empty Chapters- and Topics- dropdowns
SpecialismSel.length = 1;
//display correct values
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>
But instead of populating the second dropdown with the text for the options, it just displays the index of each dependent selection. So if I choose opt1 from the first dropdown then the second dropdown is populated with the options '0', '1', '2', '3', '4' instead of "opt6", "opt7", "opt8", "opt9", "opt10".
I would greatly appreciate any insight as to how to solve this.