[Javascript] Checking Radio Boxes with a loop

Dave Shaw dshaw256 at earthlink.net
Tue Feb 17 08:01:13 CST 2009


I see that you have several solutions. I just wanted to toss another one
at you, as it's a little different from what you have already seen.

I had a need to do the same thing, with a twist; I wanted to receive the
check boxes as an array when they got back to my application. I have an
identifier associated with each of as many as 50 check boxes, and all I
cared about was collecting a list of identifiers.

I defined the check boxes as follows (examples from a test stub I wrote
to work this out; not from my production application):

<input type="checkbox" name="cb[]" value="0" />&nbsp;First check
box<br />
<input type="checkbox" name="cb[]" value="1" />&nbsp;Second check
box<br />
<input type="checkbox" name="cb[]" value="2" />&nbsp;Third check
box<br />
<input type="checkbox" name="cb[]" value="3" />&nbsp;Fourth check
box<br />

PHP will see that, on entry, as an array named CB with values from only
the checked boxes.

Javascript on the page can iterate through the array as follows:

function validate() {
	var count = 0;
	var length;
	length = document.testform["cb[]"].length;
	for (i=0; i<length; ++i )
		if (document.testform["cb[]"][i].checked) ++count;

	if ( count == 0 ) {
		alert ( "Please check at least one checkbox" );
		return false;
	}
	else return true;
}

This solution does work, but it does require that all the check boxes
have the same name..

Hope it helps.

Dave Shaw

On Mon, 2009-02-16 at 12:00 -0600, javascript-request at lists.evolt.org
wrote:

> > -------- Forwarded Message --------
> > From: David Stoltz <Dstoltz at SHH.ORG>
> > Reply-To: JavaScript List <javascript at lists.evolt.org>
> > To: javascript at lists.evolt.org
> > Subject: [Javascript] Checking Radio Boxes with a loop
> > Date: Mon, 16 Feb 2009 08:14:29 -0500
> > 
> > 
> > Hi all,
> >  
> > I have 33 questions on a form, each with YES/NO possibilities. I'm
> > trying to add a button to "check all" yeses - Here's my code:
> >  
> > <script>
> > function qyes(){
> >  
> >                 for(i=1;i>33;i++)
> >                                 form1.question(i)[0].checked=true;
> >                 
> >  
> > }
> > </script>
> >  
> > I know this is not the right way to do this, and of course it doesn't
> > work....is there some easy way to dynamically say "question1", then
> > "question2", etc? If I replace the (i) with a number, it works of
> > course, and this is the part I'm having trouble with. I didn't want to
> > do this:
> >  
> > form1.question1[0].checked=true;
> > form1.question2[0].checked=true;
> > form1.question3[0].checked=true;
> > etc....
> >  
> > 
> > 
> > Any help?
> > Thanks!
> > 
> 
> e



More information about the Javascript mailing list