I’m planning to auto generate multiple user input boxes.
Example:
If user will input 10, auto generate 3 input field at each time. so user gets 30 input fields.
I’m finding this solution all day long but it still doesn’t work for me.
Before I looped this code it worked.
After I looped it it’s no longer working.
This is what I got before looping. CSS was pre-linked that’s why it’s aligned at one line.
// Get the input value only once
const inputValue = document.querySelector(".inputBox").value;
// Define the function outside of the loop
function btnClick(){
/// Loop until the input value is reached
let i = 0;
while (i < inputValue) {
// Create a new div element
const divElement = document.createElement("div");
const sp2 = document.querySelector(".page");
const parentdiv = sp2.parentNode;
parentdiv.insertBefore(divElement, sp2.nextSibling);
//Adding class to new div element
document.querySelectorAll("div")[2].classList.add("calBox");
const length = "<p class='first'> Length : <input type='text' class='second' value='' /> </p>";
const height = "<p class='first'> Height : <input type='text' class='second' value='' /> </p>";
const width = "<p class='first'> Width : <input type='text' class='second' value='' /> </p>";
const first = document.querySelector(".calBox");
const second = length + height + width +"<br />";
first.innerHTML = second ;
i++;
}
}
2
Answers
Remember that your code assumes that you have an HTML element with the class
inputBox
for obtaining the user input and an HTML element with the class page for inserting the generated div elements. Make sure your HTML structure aligns with these assumptions.This is a use case for the document fragment interface.