简体   繁体   中英

Linked drop down menus

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>

Yes... It should not work. because when the script is in the head section. #self1 object and the #sel2 DOM elements are not on the DOM when it executes. when It's in the body section DOM elements are created on the DOM. one way to make it work is to bring those element referencing variables inside of the function as below.

function giveSelection(selValue) {
  var sel1 = document.querySelector('#sel1');
  var sel2 = document.querySelector('#sel2');
  var options2 = sel2.querySelectorAll('option');
  sel2.innerHTML = '';
  for (var i = 0; i < options2.length; i++) {
    if (options2[i].dataset.option === selValue) {
      sel2.appendChild(options2[i]);
    }
  }
}

And believe me, It is not an efficient way. It's a best practice to include javascript to the bottom of the page and CSS to the top of the page. Including your script in the bottom of the body section is alright.

In order to use that script from head section you need to use window.onload that will fired when the DOM is ready.

In your case you can do something like that:

<head>
  <script>
const load = () => {
  sel1 = document.querySelector('#sel1');
  sel2 = document.querySelector('#sel2');
  options2 = sel2.querySelectorAll('option');
  giveSelection(sel1.value);
} 
function giveSelection(selValue) {
  sel2.innerHTML = '';
  for (var i = 0; i < options2.length; i++) {
    if (options2[i].dataset.option === selValue) {
      sel2.appendChild(options2[i]);
    }
  }
}
window.onload = load; 
  </script>
</head>

codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM