View Full Version : Looping through gaps

01-22-2010, 06:36 AM

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; }

01-22-2010, 08:33 AM
for (a = 301; a < 401; ++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':

<input id="b301" type="checkbox" value="whatever">
<input id="b302" type="checkbox" value="whatever">

etc. Then to loop through them all:

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

01-24-2010, 06:30 AM
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.