Radio Buttons and Checkboxes
Radio buttons and checkboxes are form elements used to collect user choices or preferences. They provide options from which users can select one or more items, respectively. HTML offers specific elements for creating radio buttons and checkboxes.
Radio Buttons
Radio buttons allow users to select a single option from a set of choices. To create radio buttons, use the <input>
element with type="radio"
. All radio buttons within the same group should share the same name
attribute.
Here's an example of creating radio buttons for gender selection:
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
Attributes to note:
-
id
: A unique identifier for the radio button. -
name
: All radio buttons with the samename
are part of the same group, and users can select only one option from the group. -
value
: The value associated with the selected option.
Checkboxes
Checkboxes allow users to select one or more options from a list. Each checkbox is represented by the <input>
element with type="checkbox"
.
Here's an example of creating checkboxes for newsletter subscription:
<input type="checkbox" id="subscribe-news" name="subscribe" value="newsletter">
<label for="subscribe-news">Subscribe to Newsletter</label>
<input type="checkbox" id="subscribe-updates" name="subscribe" value="updates">
<label for="subscribe-updates">Receive Updates</label>
Attributes to consider:
-
id
: A unique identifier for the checkbox. -
name
: All checkboxes with the samename
are part of the same group, and users can select multiple options from the group. -
value
: The value associated with the selected option.
Labels and the for
Attribute
Just like with text input fields, it's good practice to associate radio buttons and checkboxes with descriptive labels using the for
attribute and the element's id
. This association makes it easier for users to understand the purpose of each option and enhances accessibility.
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
Accessibility Considerations
Using labels with radio buttons and checkboxes enhances accessibility. Always include meaningful labels to ensure users can understand the options. Additionally, make use of semantic HTML elements like <fieldset>
and <legend>
to group related radio buttons or checkboxes and provide a title for the group.
In summary, radio buttons and checkboxes are crucial for gathering user selections or preferences in web forms. HTML provides specific elements and attributes for creating these input types, making it easy to design user-friendly and accessible forms.