Results 1 to 3 of 3

Thread: Looping through gaps

  1. #1
    Join Date
    Nov 2005
    Location
    Austin TX,US
    Posts
    71
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Looping through gaps

    Hi,

    I have a bunch of checkboxes with id from 301 to 400. Originally there're no gaps in between 301 to 400, so my for loop ran ok. Now there're lots of gaps and the code below doesn't work as wanted. It only works for the first couple of ids then stop at the first gap. For example, if 304 is missing, the loop will only work for 301, 302, 303; 305 and the rest won't be changed.
    How do I force the for loop to run from 301 through 400? Thanks!

    for (a = 301; a<401; a++){
    document.getElementById(a).checked = false; }

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Code:
    for (a = 301; a < 401; ++a){
    	if(document.getElementById(a)){
    		document.getElementById(a).checked = false;
    	}
    }
    Note: Technically speaking an id cannot begin with a number. You could use a letter followed by a number, say 'b':

    Code:
    <input id="b301" type="checkbox" value="whatever">
    <input id="b302" type="checkbox" value="whatever">
    etc. Then to loop through them all:

    Code:
    for (a = 301; a < 401; ++a){
    	if(document.getElementById('b' + a)){
    		document.getElementById('b' + a).checked = false;
    	}
    }
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Nov 2005
    Location
    Austin TX,US
    Posts
    71
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default

    Thanks for the input as always!
    I just came to realize I was missing an if to uncheck all boxes only when the id is not null. Without this if, the loop doesn't work as expected.
    Best!

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
  •