I'm learning JS on in school and this task is a homework and its killing me.
I need to create an input field and two buttons. The first button needs to create given number of input elements based on the first input value, second button should take all the values from new inputs and sum it.
I simply can't get the value from new input fields, i can't move from this point for week now and everything i've read didn't helped. This is the code i made so far, remember that im a complete beginner and this task is really important for me.
function myFunction() {
var i = document.getElementById("input1").value;
for (var j = 1; j <= i; j++) {
var inp = document.createElement("INPUT");
document.body.appendChild(inp);
}
}
function myFunction2() {
var arr = document.getElementsByTagName("INPUT");
for (var i = 0; i < arr.length; i++) {
var ar = document.getElementsByTagName("INPUT").value;
arr[i] = parseInt(ar);
}
for (var i = 1; i < arr.length; i++) {
var sum = sum + arr[i];
}
document.getElementById("test").innerHTML = sum;
}
<input id="input1"></input><br>
<button onclick="myFunction()">dodaj</button>
<button onclick="myFunction2()">saberi</button><br>
<p id="test"></p>
Thanks in advance
Update your myFunction2 :
function myFunction2() {
var arr = document.getElementsByTagName("INPUT");
var sum = 0;
for (var i = 0; i < arr.length; i++) {
var ar = document.getElementsByTagName("INPUT")[i].value;
sum = sum + parseInt(ar);
}
document.getElementById("test").innerHTML = sum;
}
You dont need the for loop again. Lets declare variable sum and add value into this. If you don't want to add value from first input, start for loop from 1.