robert downyqwse
robert downyqwse

Reputation: 11

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

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+; 
    }
}

Upvotes: 0

Views: 75

Answers (2)

Andr&#233; R.
Andr&#233; R.

Reputation: 1657

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">

Upvotes: 0

Shomz
Shomz

Reputation: 37711

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">

Upvotes: 3

Related Questions