Interactive Tutorial Content
Step 1
Checkboxes are used when you want to let the user select one or more options from a limited number of choices. Unlike radio buttons, checkboxes are independent—selecting one doesn't unselect others.
Step 2
To create a checkbox, we use the input tag. This is a void element, so it doesn't need a closing tag. We set the 'type' attribute specifically to 'checkbox'.
<input type="checkbox">
Step 3
A checkbox on its own is small and hard to click. To fix this and provide text, we use the <label> tag. We connect them using 'id' on the input and 'for' on the label.
<label for="tos">Accept Terms</label>
<input type="checkbox" id="tos">
Step 4
Now, clicking the text 'Accept Terms' will toggle the checkbox. This drastically improves user experience and accessibility.
<label for="tos">Accept Terms</label>
<input type="checkbox" id="tos">
Step 5
Checkpoint: Which attribute pair connects a label to an input?
<label for="x">...</label>
<input id="x">
Step 6
Sometimes you want a checkbox to be selected by default when the page loads. For this, we use the boolean attribute 'checked'. It doesn't need a value.
<label for="news">Subscribe</label>
<input type="checkbox" id="news" checked>
Step 7
See? The box is already ticked. The user can still uncheck it if they wish.
<label for="news">Subscribe</label>
<input type="checkbox" id="news" checked>
Step 8
For submitting data, we use the 'name' attribute. If you have multiple related checkboxes, they can share the same name, but have different 'value' attributes.
<input type="checkbox" name="color" value="red">
<input type="checkbox" name="color" value="blue">
Step 9
Great job! You now understand the anatomy of a checkbox. Remember, always use labels!
<h1>Done!</h1>
Step 10
Form validation is crucial for frontend development. Try the exercises below to master checkbox logic.