Languages
[Edit]
EN

HTML - checkbox input

0 points
Created by:
Inayah-Alexander
437

In this article, we would like to show you checkbox input element in HTML.

Quick solution:

// ONLINE-RUNNER:browser;

<input type="checkbox" id="one" name="one" checked />
<label for="one">Option 1</label>

<!-- or just: -->

<label>
  <input type="checkbox" name="two" />
  <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 favourite colors:</p>
  <div>
    <input type="checkbox" id="red" name="red" checked />
    <label for="red">Red</label>
  </div>
  <div>
    <input type="checkbox" id="green" name="green" />
    <label for="green">Green</label>
  </div>
  <div>
    <input type="checkbox" id="blue" name="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" name="red" checked>
      <span>Red</span>
    </label>
    <br />
    <label>
      <input type="checkbox" name="green">
      <span>Green</span>
    </label>
    <br />
    <label>
      <input type="checkbox" name="blue">
      <span>Blue</span>
    </label>
  </body>
</html>

References

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