Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Techniques for determining which box is selected in a group

There are, in general, two techniques that can be used to determine which box(s) are checked in a group. To start things off, lets first create a sample form that contains 5 radio boxes:

Which TV station do you watch most frequently?
NBC:
CBS:
ABC:
CNN:
ESPN
<form name="tv">
NBC: <input type="radio" name="station"><br>
CBS: <input type="radio" name="station"><br>
ABC: <input type="radio" name="station"><br>
CNN: <input type="radio" name="station"><br>
ESPN:<input type="radio" name="station"><br>
</form>

Perhaps you work for NBC, and would like to write a script that does one thing if NBC was selected, and another if not. Regardless of what you want the script to do, what you really want is for the script to to able to determine which box was checked. Lets examine the two techniques that will help us achieve this.

1) Use a for-loop to loop through the box array, and pick out the one that's selected

This technique calls for a loop to check the entire array of boxes, and simply pick out the one that's selected:

//a variable that will hold the index number of the selected radio button
var theone
for (i=0;i<document.tv.station.length;i++){
if (document.tv.station[i].checked==true){
theone=i
break //exist for loop, as target acquired.
}
}

2) Use the onClick event handler inside the <input> tag to react to the selected box

Another method to determine which box is selected is to use the onClick event handler. Since <input> tags in general all react to onClick events, this is a simple way to determine the selection of a surfer:

<script type="text/javascript">
var theone
</script>
<form name="tv">
NBC: <input type="radio" name="station" onClick="theone=0"><br>
CBS: <input type="radio" name="station" onClick="theone=1"><br>
ABC: <input type="radio" name="station" onClick="theone=2"><br>
CNN: <input type="radio" name="station" onClick="theone=3"><br>
ESPN:<input type="radio" name="station" onClick="theone=4"><br>
</form>

Whenever the user checks one of the radio boxes, variable "theone" is set to the index number of the box.

In the above two examples, we've shown how to determine the selection when only one box at a time can be selected. In the case where multiple seclections are possible (such as with check boxes), using a for-loop should be prefered over the onClick event to "scan" the entire array and store in the index number of all selected boxes.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.