简体   繁体   中英

Two Drop Down Menus

I wish I could use jQuery, but this has to in JavaScript. I'd appreciate the help. When "empty" (first drop down menu) is selected, I need all values from the second drop down menu (a, b, c). When "1" is selected, I need just a, b. When "2" is selected, I need just b, c.

Nothing's wrong with the drop down menu. Just had to change the values. How would I fix this in JavaScript?

First menu

<onchange="first(this);>
<option value="empty"></option>
<option value="1">1</option>
<option value="2">2</option>

Second menu

<id="second">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>

One solution that I would prefer is to set the style to none via CSS in JS. This way, the element still exists but it is just hidden from the viewer.

You can the get value of an element via [element-here].value and compare the to some value that you want. From there, you would select the second drop down option value you have and run [element-here].style.display = "none"

Another way that is more complicated that I would not recommend is to create and destroy elements entirely. Something like:

var x = document.createElement("option");
x.value = VALUE HERE;
parent.appendChild(document.createTextNode("TEXT HERE"))

This is a bit sloppy, but here's one way to do it. You have an array of data with the valid secondary values per primary value. Then you render them each time the primary list changes.

 let dropdownlist = []; dropdownlist[1] = ['a', 'b', 'c']; dropdownlist[2] = ['b', 'c']; let select = document.createElement('select'); document.getElementById('myItemList').appendChild(select); let x = 1; document.getElementById('firstddl').addEventListener('change', (e) => { //console.log(e.target.value); x = e.target.value; select.innerHTML = ''; renderDDL(dropdownlist, x) }); function renderDDL(dropdownlist, x) { dropdownlist[x].forEach(function(item) { let option = document.createElement('option'); select.appendChild(option); option.innerHTML += item; }); } renderDDL(dropdownlist, x); // Runs once
 <select id="firstddl"> <option value=1>1</option> <option value=2>2</option> </select> <div id="myItemList"> </div>

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