Results 1 to 4 of 4

Thread: What is wrong with this simple loop?

  1. #1
    Join Date
    Dec 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default What is wrong with this simple loop?

    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?

  2. #2
    Join Date
    Sep 2008
    Location
    Bristol - UK
    Posts
    842
    Thanks
    32
    Thanked 132 Times in 131 Posts

    Default

    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:

    Code:
    function hideSec() {
    	for (i=1;i<=3;i++) {
    		document.getElementById('sec' + i).style.visibility = "hidden";
    	}
    }
    That will do 1 through 3.

  3. #3
    Join Date
    Dec 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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.

  4. #4
    Join Date
    Sep 2008
    Location
    Bristol - UK
    Posts
    842
    Thanks
    32
    Thanked 132 Times in 131 Posts

    Default

    No problem, glad it worked for you, the for loop will only increment once it's done everything inside the brackets, keeps it simple.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •