HTML Course 9.3 Checkboxes and radio buttons

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 checkbox
    • name—groups related checkboxes for form submission
    • value—value submitted if checked
    • id—links to a <label>
    • checked—pre-selects the checkbox
    • disabled—makes it non-interactive
    • required—enforces at least one selection before submit
  • Grouping with a name allows 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-checked and aria-disabled are auto-managed but can be overridden if needed.

Basic checkbox example:



Grouping multiple checkboxes inside a <fieldset> with a <legend>:

Select your favorite fruits

Indeterminate State

Checkboxes support an “indeterminate” visual state via JavaScript. This state is not submitted; it’s purely presentational.





Retrieving Checkbox Values with JavaScript

Choose fruits


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 button
    • name—groups radios; only one can be checked at a time
    • value—value submitted for the checked radio
    • id—links to a <label>
    • checked—pre-selects one radio
    • disabled—makes it non-interactive
    • required—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.

Basic radio group:

Choose your gender

Pre-selecting and Disabling




Retrieving Radio Value with JavaScript

Select a color


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, and required to control default states and form validation.
  • Enhance UX with JavaScript (e.g., indeterminate checkboxes, dynamic value retrieval).


Posted

in

by

Tags:

Comments

Leave a Reply