EN
HTML - checkbox input
0
points
In this article, we would like to show you checkbox input element in HTML.
Quick solution:
// ONLINE-RUNNER:browser;
<input type="checkbox" id="field" checked />
<label for="field">Option 1</label>
or:
// ONLINE-RUNNER:browser;
<label>
<input type="checkbox" />
<span>Option 2</span>
</label>
Note:
By wrapping
input
with thelabel
we don't need to use theid
attribute that can be useful when we work with dynamically generated web pages (React, Angular, etc.).
Practical example
In this section, we create a simple checkbox by setting input
type attribute to checkbox
. We also use checked
attribute to mark the Red
as a default answer.
Note:
The key is that the
label
elements describinginput
elements are bound to the inputs using theid
-for
relation.
Runnable example:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body style="height: 105px">
<p>Choose your favorite colors:</p>
<div>
<input type="checkbox" id="red" checked />
<label for="red">Red</label>
</div>
<div>
<input type="checkbox" id="green" />
<label for="green">Green</label>
</div>
<div>
<input type="checkbox" id="blue" />
<label for="blue">Blue</label>
</div>
</body>
</html>
Alternative solution
In this section, we present an alternative solution where input
elements are wrapped with label
. The solution is equal to the first one but we don't need to specify id
attributes.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div>Choose your favourite colors:</div>
<label>
<input type="checkbox" checked>
<span>Red</span>
</label>
<br />
<label>
<input type="checkbox">
<span>Green</span>
</label>
<br />
<label>
<input type="checkbox">
<span>Blue</span>
</label>
</body>
</html>