<select name="main">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="1">5</option>
</select>
<select name="sub">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
</select>
I have 2 seperate drop downs as seen here. I want to make it so that if they select main it will show a div for main with a text box equal to they number they select(ie. 4 will show 4 main textboxes for them to fill out) which I know how to do. The problem comes with sub I want them to show a text box equal to the sub for each main select(ie if main is 3 and sub is 3 then each of the 3 main text box will be followed by 3 sub text boxes) I can make it show 3 or all but I can not figure out how to make it go based of the selection of both main and sub to ive me the exact fields I am looking for. Do I just need to set in the function for the java script that if main == x then show xyz on the function for sub?
In order to accomplish this you'll have to:
change
event on each selectvalue
attribute on each optionDemo:
const mainSelect = document.querySelector('select[name="main"]'); const subSelect = document.querySelector('select[name="sub"]'); const resultsDiv = document.getElementById("results"); mainSelect.addEventListener("change", event => { handleChange(event); }); subSelect.addEventListener("change", event => { handleChange(event); }); function handleChange(event) { let textboxes = ""; let mainCount = Number(mainSelect.value); let subCount = Number(subSelect.value); for (let i = 0; i < mainCount; i++) { let t = "<input type='text' placeholder='main' /><br/>"; for (let s = 0; s < subCount; s++) { t += "<input placeholder='sub' style='margin-left: 10px;' /><br/>" } textboxes += t; } resultsDiv.innerHTML = `<h4>Please fill these out</h4>${textboxes}`; }
<select name="main"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <br /> <select name="sub"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <div id="results"></div>
You can use onchange in the sub select:
<select name="sub" onchange="createSubInput(this)">
function createSubInput (selected) {
let mainSelectedValue = document.getElementById('main').value;
for(let i=0; i< mainSelectedValue; i++) {
for(let j=0; j< selected.value; j++) {
// todo: create sub input by each main input
}
}
}
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.