How to Construct a Checkbox in Your HTML5 Form

4 of 6 in Series: The Essentials of HTML5 Forms

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:

image0.jpg

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

<!DOCTYPE HTML>
<html lang = "en">
  <head>
    <title>formDemo.html</title>
    <meta charset = "UTF-8" />
  </head>
  <body>
    <h1>Form Demo</h1>
    <form>
       <fieldset>
         <legend>Selecting elements</legend>
         <p>
           <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>
         </p>
       </fieldset>
    </form>
  </body>
</html>

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.

blog comments powered by Disqus
Advertisement
Learning anything is easy with For Dummies eLearning!

Inside Dummies.com