HTML Course 9.3: Checkboxes and Radio Buttons
In this lesson we explore two essential form controls—checkboxes and radio buttons. Both are implemented with the <input> element, but they differ in selection behavior and grouping.
1. Input Type=’checkbox’
A checkbox allows the user to toggle a value on or off. Multiple checkboxes with the same name can be selected simultaneously.
- Attributes:
type='checkbox'—specifies a checkboxname—groups related checkboxes for form submissionvalue—value submitted if checkedid—links to a<label>checked—pre-selects the checkboxdisabled—makes it non-interactiverequired—enforces at least one selection before submit
- Grouping with a
nameallows the server to receive multiple values:- All checked values for that name are sent as an array.
- Without a name, the checkbox is not submitted.
- Accessibility:
- Use
<label for='id'>or wrap the<input>in a<label>. - ARIA states
aria-checkedandaria-disabledare auto-managed but can be overridden if needed.
- Use
Basic checkbox example:
Grouping multiple checkboxes inside a <fieldset> with a <legend>:
Indeterminate State
Checkboxes support an “indeterminate” visual state via JavaScript. This state is not submitted; it’s purely presentational.
Retrieving Checkbox Values with JavaScript
2. Input Type=’radio’
Radio buttons let the user select exactly one option from a set. All radios in a set must share the same name.
- Attributes:
type='radio'—specifies a radio buttonname—groups radios; only one can be checked at a timevalue—value submitted for the checked radioid—links to a<label>checked—pre-selects one radiodisabled—makes it non-interactiverequired—ensures one option must be chosen
- Exclusive Selection: checking one radio automatically unchecks the previously checked one in the same group.
- Accessibility:
- Wrap radios in a
<fieldset>with a<legend>for context. - Use
<label for='id'>for clear association.
- Wrap radios in a
Basic radio group:
Pre-selecting and Disabling
Retrieving Radio Value with JavaScript
Summary
- Checkboxes (
type='checkbox') allow multiple selections; radios (type='radio') enforce a single choice within a named group. - Always use
<label>for accessibility and usability. - Group related controls with
<fieldset>and<legend>. - Use attributes like
checked,disabled, andrequiredto control default states and form validation. - Enhance UX with JavaScript (e.g., indeterminate checkboxes, dynamic value retrieval).
Leave a Reply
You must be logged in to post a comment.