0

How to use loop for on javascript and use var in loop for ?

When click button. It's will be auto fill value to input type text with loop for

But not work , How can i do that ?

http://jsfiddle.net/fNPvf/16471/

function change(){    
    var price_start = document.getElementById('price_start').value;
    for (i = 1; i <= 14; i++) { 
        constance_val = i*2;
        price_month_+i+ = price_start*constance_val;
        document.getElementById('price_month_'+i+).value = price_month_+i+; 
    }
}
  • possible duplicate of [Use dynamic variable names in JavaScript](http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) (or you know.. use an array or a regular variable? Look in your console and you'll realize that you can't name a variable `price_month_+i+`) – h2ooooooo Jul 01 '15 at 11:43
  • also, your `i` is currently an implied global – Luke Jul 01 '15 at 11:44
  • 2
    http://jsfiddle.net/arunpjohny/wzd51poL/1/ – Arun P Johny Jul 01 '15 at 11:45

2 Answers2

3

You can't use i+ as a variable as it gets parsed as addition and will cause syntax errors. And you don't even need that part. You did it correctly for constance_val, but there's no need to keep values for price_month_+i because you only need them inside each loop iteration.

Here is a fixed working example, slightly optimized:

function change(){    
    var price_start = document.getElementById('price_start').value;
    for (var i = 1; i <= 14; i++) { 
        document.getElementById('price_month_'+i).value = price_start * i * 2;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="byBtn" value="Change" onclick="change()"/>
 
<input type="text" id="price_start" value="5">
<br>
<br>
<input type="text" id="price_month_1">
<br>
<br>
<input type="text" id="price_month_2">
<br>
<br>
<input type="text" id="price_month_3">
<br>
<br>
<input type="text" id="price_month_4">
<br>
<br>
<input type="text" id="price_month_5">
<br>
<br>
<input type="text" id="price_month_6">
Shomz
  • 37,421
  • 4
  • 57
  • 85
0

you had syntactic errors in your code ... and you should declare all variables as var

function change(){     
    var price_start = document.getElementById('price_start').value;
    for (var i = 1; i <= 14; i++) { 
        var constance_val = i*2;
        var price_month = price_start*constance_val;
        document.getElementById('price_month_'+i).value = price_month; 
    }
}

btw. since your button does not submit anything you should probably use <input type="button"> (or <button type="button">) instead of <input type="submit">

André R.
  • 1,627
  • 10
  • 14