How to Create a Drop-Down List in an HTML5 Form

3 of 6 in Series: The Essentials of HTML5 Forms

Drop-down lists are a common feature in web pages, and HTML5 makes creating them pretty foolproof. Drop-down lists allow you, the programmer, to specify a number of choices that visitors to your website can make without typing (a list is shown in the figure). Drop-down lists are especially nice because they don't require a lot of screen real estate — the options are visible only while the user is selecting them.

image0.jpg

Drop-down lists have an incredibly valuable attribute in that they prevent certain kinds of errors. The limited options make the response very predictable because you predetermine all the possible answers. You don't have to deal with all the crazy things users may type into a text box.

In HTML5/XHTML, drop-down lists are created by two types of object. The overall structure uses the <select> tags, while each of the possible choices has its own <option> tag, as the code for a web page with a drop-down list shows:

<!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>Select list</label>
             <select id = "myList">
               <option value = "1">one</option>
               <option value = "2">two</option>
               <option value = "3">three</option>
               <option value = "4">four</option>
             </select>
          </p>
       </fieldset>
    </form>
  </body>
</html>

The select list is a real powerhouse, so you should know how to make it:

  1. Create the <select> element first.

    The container for the list is a <select> element. The entire list is encased in the <select></select> pair.

  2. Give the select element an ID.

    You'll use this ID to refer to the element in code.

  3. Add an option element to the select element.

    It helps to indent the options to remind yourself that they're part of the select object.

  4. Give each option a value.

    The value is the response sent to a program when the user chooses an option. The user will not necessarily see the value.

  5. Indicate the text the user will see between the <option> and </option> tags.

    This can be different from the value, or the same. (That will make more sense after you do some JavaScript coding.)

  6. Add as many options as you want.

    Create a new option object for each choice you want to have available in the list.

Select boxes don't have to have the drop-down behavior. If you want the box to take up more vertical space on the page, just specify the number of rows with the size attribute.

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

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.