EN
HTML - select checkbox on click on related text
0
points
In this article, we would like to show you how to select a checkbox on click on the related text in HTML.
Quick solution:
// ONLINE-RUNNER:browser;
<input type="checkbox" id="name"/>
<label for="name">Option 1</label>
or:
// ONLINE-RUNNER:browser;
<label>
<input type="checkbox"/>
<span>Option 2</span>
</label>
Practical examples
1. Using input
and label
elements with id
-for
relation
In this example, we use input
and label
elements with id
-for
relation to enable checkbox selection on the related text click (label text).
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<input type="checkbox" id="one" />
<label for="one">Option 1</label>
<br />
<input type="checkbox" id="two" />
<label for="two">Option 2</label>
</body>
</html>
Note:
If the text inside the
label
element wasn't bound by anid
-for
relation, then the text could not be clicked.
2. Wrapping input
with label
element
In this example, we present how to enable checkbox selection when you click the related text from label by wrapping the input
element with label
. This solution doesn't need the id
and for
attributes to specify the relation.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<label>
<input type="checkbox" />
<span>Option 1</span>
</label>
<br />
<label>
<input type="checkbox" />
<span>Option 2</span>
</label>
</body>
</html>
Note:
If you put the text (e.g
<span>Option 1</span>
) outside thelabel
element, you won't be able to click the related text anymore.