bernie2436
bernie2436

Reputation: 23921

writing multiple lines in a for loop

I'm fiddling with javascript to get the hang of it. I am trying to built an x by x grid programatically--which I'll eventually try to get to be minesweeper. I have a function to write a single row with x entries. I have another function that loops, calling the single row function x times. The idea is that by calling the row function x times, I'll get an x by x grid. But in my current code, the looping function is calling the single line function 1 time and I can't figure out why. When I use alerts to count iterations, the loop fires five times--but not when the writeOneRow function is included. I get the same behavior in IE and Chrome. Can anyone point out my (likely bonehead) error:

<html>
<body>
<script type="text/JavaScript">

function writeRows(loop) {
         for (i=0;i<loop;i++){
             writeOneRow(loop);  //this is only called once. Why?
         }
}

function writeOneRow(num) {
         var b = "<Div style='float:left; border-style:solid; margin:10px'> Test </div>"
         var string =""
         for (i=0;i<num;i++){
             string= string+ b ;
             }
         var line = document.createElement('div');
         line.innerHTML = string ;
         document.body.appendChild(line);
}  
</script>

<a href="#" onclick="javascript:writeRows(5);return false;">InsertRow</a>
</body>
</html>

Upvotes: 1

Views: 2781

Answers (3)

Joshua Glazer
Joshua Glazer

Reputation: 271

My JavaScript is a bit rusty, but you never declare i as a local variable, so I think both for loops are modifying the same i and thus it hits 5 inside the second function and the first loop only runs once.

Try adding var i; in both your functions before the for loops and that will create a local variable in each case and should fix the problem. Cheers!

Upvotes: 2

evotopid
evotopid

Reputation: 5429

I'm not sure if I understood you correctly, but this could help...

Change the line:

line.innerHTML = string ;

To:

line.innerHTML = line.innerHTML + string;

Than you won't need the second for loop anymore you could just do:

var string = b;

Upvotes: 0

epascarello
epascarello

Reputation: 207537

Your variable i is a global. Use var to make them local.

for (var i=0;i<num;i++){
...
for (var i=0;i<num;i++){

Upvotes: 7

Related Questions