PDA

View Full Version : What is wrong with this simple loop?



crane
12-14-2010, 11:11 PM
I have this simple loop that doesn't work:

function hideSec() {
var i=0;
for (i=0;i<=3;i++) {
document.getElementById('sec' + i).style.visibility = "hidden";
}
}

But if I do it without the loop it works:

function hideSec() {
var i=1;
document.getElementById('sec' + i).style.visibility = "hidden";
i=2;
document.getElementById('sec' + i).style.visibility = "hidden";
i=3;
document.getElementById('sec' + i).style.visibility = "hidden";
}

What's wrong?

Schmoopy
12-14-2010, 11:22 PM
It's probably because 'sec0' doesn't exist - and it's stopping the script when it can't change the style of that element, try:



function hideSec() {
for (i=1;i<=3;i++) {
document.getElementById('sec' + i).style.visibility = "hidden";
}
}


That will do 1 through 3.

crane
12-15-2010, 05:54 PM
Thank you, Schmoopy. It works! Now I can see that my problem is that I thought that (i=0;i<=3;i++) meant that Javascript sets the value of i at zero to start with, checks if it is <= three, then updates it by one to a value that will then be 1, and only then does it move to the first line of what it must execute in the loop. However, now I can see that the demand (i=0;i<=3;i++) is merely informing Javascript what it has to do with the loop. In fact I was asking Javascript to do the loop four times.

Many thanks, i'm underway now.

Schmoopy
12-15-2010, 06:24 PM
No problem, glad it worked for you, the for loop will only increment once it's done everything inside the brackets, keeps it simple.