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!