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.

SCRIPTING CHECKBOXES

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.