Categories:

Grouping multiple boxes together

We rarely see only one radio or checkbox by itself in a form. The nature of them requires that they exist as a group:

A group of radio buttons:

Male:   
Female:

A group of check boxes:
Sports:
Reading:
Computers:
Sleeping:

By now, we know that the default way to access any one box is through its name. Having said that, imagine having a group of 50 radio buttons. Accessing them would require us to give each and every button an unique name. Furthermore, in a scenerio where we need to apply a loop through all of the radio buttons, it will mean manually writing out 50 lines of code to access and reach every of the 50 buttons. Hardly even an acceptable thought.

So you say to yourself, like you often do as you gaze towards the sky: "There must be something better out there". Well, I hate to break it to you, but there isn't- in life, that is. In JavaScript, however, there is. There is a technque that will allow us to easily and efficiently access a radio or check box in a group. The key is to give each box the same exact name. By doing so, JavaScript creates an array out of the boxes with this same name, and allows us to access the individual boxes as an array element. Lets demonstrate this concept with a form that contains 10 check boxes:

<form name="example">
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
<input type="checkbox" name="myboxes"><br>
</form>

In the above form, we gave each box the same name. See just how easy it is now to access the individual check boxes:

//accesses the 3rd checkbox
document.example.myboxes[2]
//accesses the last checkbox
document.example.myboxes[9]
//accesses each and every one of the boxes
for (i=0;i<document.example.myboxes.length;i++)
document.example.myboxes[i]=//do whatever

As you can see, by giving each checkbox the same name, they turn into an array of checkboxes, and we all know the beauty of arrays in terms of power and versatility.

In the final part of our tutorial, lets wrap things up by examining some techniques available in determining which box is selected in a group.