How to Construct a Checkbox in Your HTML5 Form - dummies

How to Construct a Checkbox in Your HTML5 Form

By Andy Harris

Sometimes, you want your web page users to indicate whether information is true or false. The HTML5 checkbox element is perfect for this kind of input because the user can click to select or deselect the option. Checkboxes are another variant of the versatile input tag. Checkboxes for Green Eggs and Ham are shown in the figure:


Checkboxes often appear in groups, but they are independent of each other. The code for a web page with checkboxes looks like:

<html lang = "en">
    <meta charset = "UTF-8" />
    <h1>Form Demo</h1>
         <legend>Selecting elements</legend>
           <label>Check boxes</label>
             <input type = "checkbox"
                 id = "chkEggs"
                 value = "greenEggs" />
             <label for = "chkEggs">Green Eggs</label>
             <input type = "checkbox"
                 id = "chkHam"
                 value = "ham" />
             <label for = "chkHam">Ham</label>

You typically attach a label to the text box so that the user can click the checkbox or the associated label to make a selection.

To build a checkbox, follow these steps:

  1. Begin with an input element.

  2. Set the type attribute to checkbox.

    This clarifies that the input element is a checkbox and places a small checkable box on the screen.

  3. Give the element an id field so that your code can work directly with the element.

  4. Specify a value.

    You can attach a value to a checkbox. The user won’t see the value (unless you choose to make the label look just like the value).

  5. Add a label.

    Checkboxes really need to have a label associated with them so that the user understands what the checkbox is about. The label is usually positioned to the right of the checkbox.

  6. Add the for attribute to the label.

    The label has a special attribute called for, which allows you to specify which input element the label corresponds to. Place the id value of the checkbox into this attribute of the label.

    This is especially useful for checkboxes because, in most browsers, the user can click either the label or the checkbox to trigger the selection. Associating the label to the checkbox gives the user a larger target to click and makes the form easier to use.

HTML forms don’t do anything on their own. You’ll need to add some sort of programming in JavaScript or HTML to make the form do something.