Languages
[Edit]
EN

HTML - checkbox input

0 points
Created by:
Inayah-Alexander
767

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 the label we don't need to use the id 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 describing input elements are bound to the inputs using the id - 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>

References

Alternative titles

  1. HTML - input type checkbox
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

HTML - input element types

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join