Input value always gets into if condition first even am parsing it to parseInt() and when page refreshed with a number it gets into else condition, like its not registering the inputValue at first place, also if i add a submit event rather an click one event doesnt fires up.
HTML <div class="addHere"></div> <div class="inputs"> <input type="text" maxlength="1" class="inputValue" placeholder="insert numbers:"/> <button class="btn">+</button> </div> javaScript // this line was modified const inputValue = parseInt(document.querySelector(".inputValue").value); const div = document.querySelector(".addHere"); document.querySelector(".btn").addEventListener("click", addInputs); fucntion addInputs() { if(isNaN(inputValue)) { alert("Wrong input"); } else { for ( let i = 1; i <= inputValue; i++) { const form = document.createElement("form"); form.method = "post"; form.action = "#"; const input1 = document.createElement("input"); input1.type = "text"; input1.maxLength = "12"; input1.className = "factor"; input1.required = true; const input2 = document.createElement("input"); input2.type = "text"; input2.maxLength = "1"; input2.className = "priority"; input2.required = true; const br = document.createElement("br"); form.appendChild(br.cloneNode()); form.appendChild(input1); form.appendChild(input2); form.appendChild(br.cloneNode()); div.appendChild(form); } const sub = document.createElement("button"); sub.type = "submit"; sub.value = "Submit"; sub.className = "subButton"; sub.textContent = "Submit"; div.appendChild(sub); } }
Advertisement
Answer
You’re recording the value of the input on page load, so at first it is empty.
Move this line
const inputValue = parseInt(document.querySelector(".inputValue").value);
to be the first line of your function that runs after clicking your button.
function addInputs() { const inputValue = parseInt(document.querySelector(".inputValue").value);
Also it is probably best to use ID’s for those elements and select them by their ID’s rather than a class. ID’s are unique so there can only be one of them on the page.
I also corrected typos in those lines, missing ” and misspelled function.