views:

78

answers:

3

I have this for loop, and it seems to be repeating the first loop twice (x=0) and then not doing the last one (x=2)

for (x=0;x<=2;x++)
    {
        if (document.getElementById("sub"+catCount+x).value != "")
        {
            if (nonums.test(document.getElementById("sub"+catCount+x).value))
            {
                total = total + parseFloat(document.getElementById("sub"+catCount+x).value);
            }
        }
        alert(x);
    }

In other words, I get two alert boxes with "0" in them, then one with "1" in it, and that's it.

Can anyone tell me what I'm not seeing here? Why doesn't it just progress through the loop normally (0,1,2)?

+1  A: 

that is literally the only spot I use the variable x on any page.

It works for me.

for (x=0;x<=2;x++)
{
  alert(x);
}

You can test it at console.

Sarfraz
that exact snippet of code produces the same results.
Jimmy
@Jimmy: It says `0` then `1` and `2` for me.
Sarfraz
+2  A: 

I don't think you want the variable x to be global in scope. Try it with the "var" keyword:

for (var x=0;x<=2;x++)
...

I can paste this in my address bar and it will produce 0, 1, 2.

javascript:for (var x=0;x<=2;x++) {alert(x);}

I tried it in IE, FF and Chrome.

JBrooks
didn't help. now it goes "0, 0, 1, 1"???
Jimmy
+1  A: 

Never mind.

It was something completely unrelated.

I feel stupid.

Jimmy
You over-simplified the code in the question and left something out?
Brock Adams
yep. but the problem code was from a different page.
Jimmy