Chapter 30. Scripting Checkboxes and Radio Buttons

Checkboxes and radio buttons are used in two different ways. You use radio buttons for a list of multiple options that are mutually exclusive and from which users can select only one. Checkboxes are for multiple options from which users can choose any number. Despite this distinction, the primary purpose of both is to give users a number of options to choose from.

They also have something else in common: Their DOM objects share the same properties, methods, and events. But scripting them can be a little different due to how they are represented in the DOM. This lesson teaches you how to write JavaScript against these controls, starting with the checkbox.


You generate checkboxes by using the <input/> element and setting its type attribute to checkbox, as shown in the following HTML:

<input type="checkbox" name="color" value="Red" checked="checked" />

This HTML creates a checkbox named color with a value of Red that is checked by default because of the presence of the checked attribute. In the DOM, just as with all other form controls, the name and value attributes are available to you as properties of the checkbox's DOM object. The checked attribute maps to a property of the same name, but the property's value is either true or false (as opposed to the checked attribute's value in the previous HTML code). So you can change the checked state of a checkbox by assigning a Boolean value to the checked property, like this: ...

Get JavaScript® 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.