Two HTML-select boxes linked to each other

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

Hellloooooo... I have two <select> inputs like this

<select id="sel1">   <option value="a">a</option>   <option value="b">b</option> </select>  <select id="sel2">   //if 'a' is selected above,   //<option>apple</option>, <option>airplane</option>   //if 'b' is selected above,   //<option>banana</option>, <option>book</option> </select> 

And I want to list different sets of options according to the selection in sel1. I could get the selected value using onchange attribute like this:

<select id="sel1" onchange="giveSelection(this)"> <script type="text/javascript">   function giveSelection(sel) {     var selected = sel.value;   } </script> 

But I can't come up with a way to use this value to output different select options in sel2. Help please!

回答1:

You almost got there. As you already got sel1's value, the rest is to filter options for sel1 based on the value.

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);
<select id="sel1" onchange="giveSelection(this.value)">   <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>


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!