0

I am attempting to create a number of functions within a for loop. I think I have the variables all correct - I'm just struggling with the function. It is always calling the function with the last variables input in (it is just trying to add 2 numbers and output the result to the correct div - num1 + input1 = total1, num2 + input2 = total2 etc - outputting into the last div currently) - I think this is because I haven't numbered the function and I am unsure of the syntax to do so - however I may be completely off the point as well...

<div id="num1">11</div>

<input type=number value=2 id="input1">

<div id="total1">0</div>

<div id="num2">11</div>

<input type=number value=2 id="input2">

<div id="total2">0</div>

<script type="text/javascript">

for(var x=1; x<3; x++){

var num = "num"+x;
var input = "input"+x;
var total = "total"+x;
var element = "element"+x;
var inputelement = "inputelement"+x;
var thesum = "thesum"+x;

element = document.getElementById(num),
inputelement = document.getElementById(input),
thesum = document.getElementById(total);
document.getElementById(input).onchange = function() {
thesum.innerHTML = parseInt(element.innerHTML) + parseInt(inputelement.value);
};
};

</script>

Many thanks in advance for any help or advice.

shubbard
  • 5
  • 3
  • Check these questions, I think they target the same problem: https://stackoverflow.com/questions/19586137/addeventlistener-using-for-loop-and-passing-values and https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – chrki Jul 07 '17 at 22:28
  • By the time the event handler function is executed, the values of `thesum`, `element` and `inputelement` have already progressed to what they were assigned when `x = 3`. Several solutions exist. One easy is to change `var` by `let` so you get separate variables for each iteration. – trincot Jul 07 '17 at 22:31
  • @trincot thank you for the advice, worked perfectly. Apologies for the duplicate question – shubbard Jul 07 '17 at 22:36

0 Answers0