Home

How to Use Check Boxes and Radio Buttons in Your HTML5 Form

|
Updated:  
2016-03-26 14:03:44
|
HTML5 and CSS3 All-in-One For Dummies
Explore Book
Buy On Amazon

When creating a data collection form for your website, if only a finite set of possible values is available to the user, you can give him a collection of options to choose from:

  • Check boxes: Choose more than one option.

  • Radio buttons: Choose only one option.

    Radio buttons differ from check boxes in an important way: Users can select a single radio button from a set of options but can select any number of check boxes (including none, one, or more than one).

If many choices are available (more than half a dozen), use a drop-down list instead of radio buttons or check boxes.

To create radio buttons and check boxes, take these steps:

  1. Use the element with the type attribute set to radio or checkbox.

  2. Create each option with these attributes:

    • name: Give the option a name.

    • value: Specify what value is returned if the user selects the option.

You can also use the checked attribute (with a value of checked) to specify that an option should be already selected when the browser displays the form. This is a good way to specify a default selection.

This markup shows how to format check box and radio button options:

<form action="bin/guestbook.php" method="post">
<p>What are some of your favorite foods?</p>
<ul style="list-style-type: none;">
  <li><input type="checkbox" name="food" value="pizza" checked="checked">
    Pizza</li>
   <li><input type="checkbox" name="food" value="icecream">Ice Cream</li>
   <li><input type="checkbox" name="food" value="eggsham">Green Eggs 
        and Ham</li>
</ul>
<p>What is your gender?</p>
<ul style="list-style-type: none;">
  <li><input type="radio" name="gender" value="male">Male</li>
  <li><input type="radio" name="gender" value="female" checked="checked">
    Female</li>
</ul>
</form>

The result is shown in this figure.

image0.jpg

In the preceding markup, each set of options uses the same name for each input control but gives a different value to each option. You give each item in a set of options the same name to let the browser know they’re part of a set.

If you want to, you can select as many check boxes as you like by default in the page markup — simply include checked="checked" in each element you want selected in advance.

About This Article

This article is from the book: 

About the book author:

Ed Tittel is a 28-year veteran of the computer industry. A seasoned author and consultant, Ed has more than 140 books to his credit.

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.