0

I got stuck on a really simple task. I have several JavaScript function, but I am bad at JS so cannot solve this. I need to put it inside the for loop. Please help. My solution doesn't work. The logic is down - my code is awful help.

FUNCTION WITHOUT LOOP

<script>
var c1 = 14.94;
var c2 = 12.20;

function changeq() {
    var q1 = parseInt(document.getElementById('q1').value);
    var t1 = q1 * c1;
    var total1 = t1.toFixed(2);
    document.getElementById('ukupno1').innerHTML = total1;
}

function changeq(2) {
    var q2 = parseInt(document.getElementById('q2').value);
    var t2 = q2 * c2;
    var total2 = t2.toFixed(2);
    document.getElementById('ukupno2').innerHTML = total2;
}
</script>

FUNCTION INSIDE LOOP - WRONG

 <script>
    var c1 = 14.94;
    var c2 = 12.20;
var fncs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = (function(index) {
    return function changeq[i] {
    var q[i] = parseInt(document.getElementById('q[i]').value);
    var t[i] = q[i] * c[i];
    var total[i] = t[i].toFixed(2);
    document.getElementById('ukupno[i]').innerHTML= total[i];
    }
    </script>
jfriend00
  • 683,504
  • 96
  • 985
  • 979
mpavlovic89
  • 749
  • 3
  • 16
  • 37
  • 1
    This is a very common issue for people who are learning JavaScript to run into. You need to use `closures`, as linked to in my other comment. That said, you'll also need to change some of your encoded strings to be `'ukupno[' + i + ']'` – Jeremy J Starcher Aug 11 '14 at 01:58
  • Long story short, `i` does not have the value you were expecting since `i` is not locally scoped. – Derek 朕會功夫 Aug 11 '14 at 02:12
  • Your second attempt would work if you used the proper syntax and closed all open parens and braces and passed the `index` variable to it. You really ought to learn to look at the error console to see your own syntax errors before coming to StackOverflow. – jfriend00 Aug 11 '14 at 02:13

0 Answers0