I am trying to create 2 drop down menus, where the first list is linked to the second list (the second list is updated each time I select something in the first one). I have some code that works, but it seems a little bit confusing to me.
Also this is working only if the script is in the body. If I move it to the head it doesnt work.
Why? Can the same thing be implemented in some other way for example with the use of a 2d array, with the use on only Javascript?
var sel1 = document.querySelector('#sel1');
var sel2 = document.querySelector('#sel2');
var options2 = sel2.querySelectorAll('option');
function giveSelection(selValue) {
sel2.innerHTML = '';
for (var i = 0; i < options2.length; i++) {
if (options2[i].dataset.option === selValue) {
sel2.appendChild(options2[i]);
}
}
}
giveSelection(sel1.value);
<h1><b>Title</b></h1>
<select id="sel1" onchange="giveSelection(this.value)">
<option value="0"></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="sel2">
<option data-option="a">apple</option>
<option data-option="a">airplane</option>
<option data-option="b">banana</option>
<option data-option="b">book</option>
</select>