How to Create Checkbox in HTML: Simple Guide with Examples
To create a checkbox in HTML, use the
<input> element with the attribute type="checkbox". You can add a name and value attribute to identify the checkbox and its value when selected.Syntax
The basic syntax for a checkbox in HTML uses the <input> tag with type="checkbox". You can add a name to group checkboxes and a value to specify what is sent when the checkbox is checked.
- type="checkbox": Defines the input as a checkbox.
- name: Groups checkboxes or identifies the input.
- value: The value sent if the checkbox is checked.
- checked (optional): Makes the checkbox selected by default.
html
<input type="checkbox" name="example" value="value1">
Output
A small square box that can be checked or unchecked.
Example
This example shows three checkboxes with labels. Users can select one or more options. The first checkbox is checked by default.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Checkbox Example</title> </head> <body> <form> <label><input type="checkbox" name="fruit" value="apple" checked> Apple</label><br> <label><input type="checkbox" name="fruit" value="banana"> Banana</label><br> <label><input type="checkbox" name="fruit" value="cherry"> Cherry</label> </form> </body> </html>
Output
Three checkboxes labeled Apple (checked), Banana, and Cherry, each can be checked or unchecked independently.
Common Pitfalls
Common mistakes when creating checkboxes include:
- Forgetting to use the
nameattribute, which makes it hard to identify the checkbox in form data. - Not associating labels properly, which hurts accessibility and usability.
- Using
checkedwithout a value, which can confuse users.
Always wrap checkboxes with <label> or use for attribute to link labels for better accessibility.
html
<!-- Wrong way: no label --> <input type="checkbox" name="subscribe" value="yes"> <!-- Right way: with label --> <label><input type="checkbox" name="subscribe" value="yes"> Subscribe to newsletter</label>
Output
The right way shows a checkbox with clickable label text 'Subscribe to newsletter'. The wrong way shows only the checkbox without label.
Quick Reference
| Attribute | Description |
|---|---|
| type="checkbox" | Defines the input as a checkbox |
| name | Groups checkboxes or identifies the input in form data |
| value | Value sent when checkbox is checked |
| checked | Makes checkbox selected by default |
| disabled | Disables the checkbox so it cannot be changed |
Key Takeaways
Use to create a checkbox in HTML.
Always include a name attribute to identify the checkbox in form submissions.
Wrap checkboxes with labels for better accessibility and usability.
Use the checked attribute to set a checkbox as selected by default.
Avoid missing labels or names to prevent confusion and accessibility issues.