How can I create an HTML checkbox with a label that is clickable (this means that clicking on the label turns the checkbox on/off)?
Clickable Checkbox LabelWithout label tags, users can't click the label to tick the checkbox. Instead, they have to click the checkbox itself. This causes users to struggle because the checkbox is a small target to hit especially for motor-impaired users.
The <input type="checkbox"> defines a checkbox. The checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices. Tip: Always add the <label> tag for best accessibility practices!
Wrap the checkbox within a label
tag:
<label><input type="checkbox" name="checkbox" value="value">Text</label>
for
AttributeUse the for
attribute (match the checkbox id
):
<input type="checkbox" name="checkbox" id="checkbox_id" value="value"> <label for="checkbox_id">Text</label>
NOTE: ID must be unique on the page!
Since the other answers don't mention it, a label can include up to 1 input and omit the for
attribute, and it will be assumed that it is for the input within it.
Excerpt from w3.org (with my emphasis):
[The for attribute] explicitly associates the label being defined with another control. When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the element's contents.
To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.
Using this method has some advantages over for
:
No need to assign an id
to every checkbox (great!).
No need to use the extra attribute in the <label>
.
The input's clickable area is also the label's clickable area, so there aren't two separate places to click that can control the checkbox - only one, no matter how far apart the <input>
and actual label text are, and no matter what kind of CSS you apply to it.
Demo with some CSS:
label { border:1px solid #ccc; padding:10px; margin:0 0 10px; display:block; } label:hover { background:#eee; cursor:pointer; }
<label><input type="checkbox" />Option 1</label> <label><input type="checkbox" />Option 2</label> <label><input type="checkbox" />Option 3</label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With