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.
JavaScript
x
56
56
1
HTML
2
<div class="addHere"></div>
3
<div class="inputs">
4
<input type="text" maxlength="1" class="inputValue" placeholder="insert numbers:"/>
5
<button class="btn">+</button>
6
</div>
7
8
javaScript
9
// this line was modified
10
const inputValue = parseInt(document.querySelector(".inputValue").value);
11
12
const div = document.querySelector(".addHere");
13
14
document.querySelector(".btn").addEventListener("click", addInputs);
15
16
fucntion addInputs() {
17
if(isNaN(inputValue)) {
18
alert("Wrong input");
19
} else {
20
for ( let i = 1; i <= inputValue; i++) {
21
const form = document.createElement("form");
22
form.method = "post";
23
form.action = "#";
24
25
const input1 = document.createElement("input");
26
input1.type = "text";
27
input1.maxLength = "12";
28
input1.className = "factor";
29
input1.required = true;
30
31
const input2 = document.createElement("input");
32
input2.type = "text";
33
input2.maxLength = "1";
34
input2.className = "priority";
35
input2.required = true;
36
37
const br = document.createElement("br");
38
39
form.appendChild(br.cloneNode());
40
form.appendChild(input1);
41
form.appendChild(input2);
42
form.appendChild(br.cloneNode());
43
44
div.appendChild(form);
45
}
46
47
const sub = document.createElement("button");
48
sub.type = "submit";
49
sub.value = "Submit";
50
sub.className = "subButton";
51
sub.textContent = "Submit";
52
53
div.appendChild(sub);
54
}
55
}
56
Advertisement
Answer
You’re recording the value of the input on page load, so at first it is empty.
Move this line
JavaScript
1
2
1
const inputValue = parseInt(document.querySelector(".inputValue").value);
2
to be the first line of your function that runs after clicking your button.
JavaScript
1
3
1
function addInputs() {
2
const inputValue = parseInt(document.querySelector(".inputValue").value);
3
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.