Categories:
Partners

Manipulating radio and check boxes in JavaScript

Radio and check boxes are an intergral part of forms that allow a surfer to make a selection with a simple click of the mouse. These form controls are not nearly as commonly manipulated in JavaScript when compared to <textarea> elements, mainly because a lot of developers aren't aware that radio and check boxes can too be dynamically accessed and their values changed using JavaScript. In this tutorial, we'll show just how that's done.

The distinction between a radio and a check box

Before we officially jump in, its important to first make sure that everyone's clear on the distinction between a radio and a check box.

What's your gender?

Male:   
Female:

What are your hobbies?
Sports:
Reading:
Computers:
Sleeping:

Only one radio box in a group can be selected at a time, whereas with check boxes, multiple selections are allowed. I hope no one finds the need to use checkboxes for the first question!

How to access a radio/check box in JavaScript

So, how exactly does one access a radio or checkbox in JavaScript? Well, like you would with any other form element- through its name. Whether it is a radio or a check box makes no difference to JavaScript. The below defines a radio button with the name "test", and uses JavaScript to access it:

<form name="example">
<input type="radio" name="test">
</form>

<script>
//accesses the button called "test"
document.example.test
</script>

Changing the state of a box

Accessing a box (radio or check) by itself is useless if we can't go on to manipulate the state of it. The state of a box can be of two things- "on" when its selected, and "off", when its not. This state is represented in JavaScript by a boolean property called "checked":

property function
checked Contains a boolean value indicating whether a box is selected or not. Writable.

Using this property, we can not only determine the state of a box, but change it as well, by assigning either a value of "true" or "false" to it.

//alerts whether a box is checked
alert(document.example.test.checked)

//Dynamically selects a box
document.example.test.checked=true

Now that we know how to access and manipulate a single box, lets expand our workarea to cover an entire group of boxes.

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