Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Dreamweaver Developer Center /

Understanding HTML5 intelligent forms – Part 1: New input elements

by David Powers

David Powers
  • http://foundationphp.com/

Content

  • Specialized text input elements
  • Date- and time-related input
  • Creating a slider input
  • Using a datalist to display options for text input
  • Further improvements to forms

Created

10 August 2011

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
Dreamweaver forms HTML5 JavaScript

Requirements

Prerequisite knowledge

Basic understanding of HTML forms.

User level

Intermediate

Required products

  • Dreamweaver (Download trial)

Sample files

  • html5_forms_pt1.zip

Forms are everywhere on the web. They're essential for gathering information through surveys, feedback pages, blog comments, and shopping carts. Thanks to HTML5, online forms are about to get a whole lot better.

HTML5 form features fall into two categories: dedicated input elements for data such as email addresses and numbers, and new attributes that allow you to specify whether an item is required, minimum and maximum values, and so on. The latest versions of browsers have already begun implementing many of these features. Once they're fully implemented, they'll eliminate the need to use JavaScript for client-side form validation (although you should still validate user input on the server for security reasons). And the good news is that you can start implementing these features right away, because they have been designed to be backwards compatible with HTML 4.01 and XHTML 1.0. Older browsers that don't recognize the new input elements simply treat them as ordinary text input fields. So, with one minor exception (the range input type), you can use HTML5 form features safely in all browsers.

In this first part of a two-part tutorial, I'll describe the new input elements and the <datalist> element, which allows you to suggest options for a text input field. In Part 2, you'll learn about the HTML5 form attributes.

Specialized text input elements

Figure 1 shows a simple online form that contains a text field, check box, radio (or option) buttons, file upload field, and a Submit button.

Figure 1. The HTML <input> tag has a wide range of uses.
Figure 1. The HTML <input> tag has a wide range of uses.

The underlying HTML markup for this form looks like this (see also html4_input.html in the example files that accompany this tutorial):

<form method="post" enctype="multipart/form-data" name="form1"> <p> <label for="name">Name:</label> <input type="text" name="name" id="name"> </p> <p> <input type="checkbox" name="terms" id="terms"> <label for="terms">I have read the terms and conditions</label> </p> <p> <label> <input type="radio" name="gender" value="f" id="gender_0"> Female</label> <br> <label> <input type="radio" name="gender" value="m" id="gender_1">Male</label> </p> <p> <label for="file">Upload file:</label> <input type="file" name="file" id="file"> </p> <p> <input type="submit" name="send" id="send" value="Submit"> </p> </form>

The notable feature of this form is that every element uses the <input> tag. What changes the look and behavior of each element is its type attribute. So, instead of having a dedicated tag for check boxes, for example, and another for radio buttons, the same HTML tag is used for a variety of purposes. Of course, other tags, such as <select> and <textarea> are also used in forms, but the <input> tag is the most versatile. What's more, the default value of the type attribute is text . So, if the attribute is missing—or the browser doesn't recognize it—the form displays a simple text field.

HTML5 takes advantage of this default behavior to define no fewer than 13 new form elements by expanding the range of accepted values for the type attribute. Browsers that understand the new values handle form input according to the HTML5 specification. Older browsers simply display standard text fields. It's a win-win situation, meaning that you can start incorporating the new input types in your forms right now. Table 1 lists the specialized text input types, of which there are six. I'll deal later with the remaining types, which are dedicated to dates and time, and a number slider.

Table 1. HTML5 specialized text input types

Type

Description

search

Search field

tel

Single-line text field for phone number

url

Single-line text field for URL

email

Single-line text field for one or more email addresses

number

Single-line text field or number stepper

color

Color picker

To add one of these new input types to a form, you simply create a text input field and change its type attribute in the HTML markup. Code hints in Dreamweaver CS5.5 support all HTML5 input types (see Figure 2).

Figure 2. Dreamweaver code hints support the HTML5 input types.
Figure 2. Dreamweaver code hints support the HTML5 input types.

You can also change the type attribute by highlighting the <input> tag, and selecting the appropriate value from the pop-up menu in the General category of the Tag Inspector panel (Window > Tag Inspector), as shown in Figure 3.

Figure 3. The Dreamweaver Tag Inspector panel also supports the HTML5 input types.
Figure 3. The Dreamweaver Tag Inspector panel also supports the HTML5 input types.

A sample of each new input type listed in Table 1 is in html5_input.html in the example files that accompany this tutorial. The following sections describe each one briefly.

Creating a search field

Setting the type attribute of an <input> tag to search is mainly of cosmetic value. It doesn't automatically create a search field. As with all form elements, you still need to code the server-side logic yourself or use a third-party script. Most browsers simply display a search field as a normal text field. However, Safari and Chrome on Mac OS X automatically add rounded corners to match the operating system's standard look (see Figure 4).

Figure 4. WebKit browsers automatically style search fields on Mac OS X.
Figure 4. WebKit browsers automatically style search fields on Mac OS X.

Creating a dedicated field for phone numbers

There's no internationally agreed format for telephone numbers, so setting the type attribute to tel doesn't appear all that useful—until you test it on a smartphone or tablet, that is. As Figure 5 shows, tapping a tel input field on an iPod touch, iPhone, or similar device brings up the phone keypad. This not only makes it a lot easier to enter the phone number, but it also prevents invalid characters from being entered on a mobile device.

Figure 5. Using a dedicated phone field is more user-friendly on a mobile device.
Figure 5. Using a dedicated phone field is more user-friendly on a mobile device.

Desktop browsers currently don't treat tel input fields differently from ordinary text fields. However, if you want to enforce a particular format for a telephone number, you can use the pattern attribute, which you'll learn about in Part 2 of this two-part tutorial.

Creating a URL input field

Setting the type attribute to url also brings up the appropriate keypad on modern mobile devices. The most recent versions of desktop browsers, apart from Internet Explorer (IE) 9 and Safari 5.1, automatically validate the user input when the form is submitted. However, in Firefox 5, Chrome 13, and IE 10 Preview 2 the validation is stricter than you might expect. As Figure 6 shows, "www.adobe.com" is rejected as not being a valid URL.

Figure 6. Chrome 13 rejects a URL without the leading http://.
Figure 6. Chrome 13 rejects a URL without the leading http://.

Firefox 5, Chrome 13, and IE 10 Preview 2 all insist on a fully qualified URL beginning with http://. On the other hand, Opera 11.50 automatically inserts the http:// for you if it has been omitted. However, Opera doesn't perform any other validation. For example, if you enter "adobe" in the field, it simply converts it to "http://adobe" and submits it, even though it's not the correct format for a URL.

Clearly, there's some way to go before browsers handle URL fields in a consistent, user-friendly way.

Creating an email input field

Support for the email input type is similar to that for URLs. If you set the type attribute to email, mobile devices display the appropriate keypad when the user taps the field. On a desktop computer, Firefox 5, Chrome 13, IE 10 Preview 2, and Opera 11.50 prevent the form from being submitted if the input contains illegal characters or doesn't include an @ mark.

A really useful feature of the email input type is that it prevents users from attempting to stuff the field with multiple email addresses. Only a single address is permitted unless you also set the multiple attribute on the <input> tag like this:

<input type="email" name="email" id="email" multiple>

Creating a number field

Setting the type attribute to number creates a field intended for numerical input. On iOS, tapping the field displays a numeric keypad, but you can also switch to alphabetic input. On Android, however, the keypad permits only numbers and a limited range of punctuation characters.

The latest versions of all mainstream desktop browsers, except IE and Firefox 5, display a number spin box similar to Figure 7. Clicking the up arrow to the right of the box increases the number in the field. Clicking the down arrow reduces the number.

Figure 7. Number spin boxes make it easier to enter numeric values.
Figure 7. Number spin boxes make it easier to enter numeric values.

Currently, browsers don't check whether the submitted value is actually a number, so a user could type "ten" in the field, and the form would be submitted without problem. However, you can enforce the use of a number with the pattern attribute (see Part 2).

Adding a color picker

Currently, the only browser that supports the color type is Opera. It displays a color box, which expands to display a set of common color swatches (see Figure 8).

Figure 8. Opera displays a color picker when type is set to color.
Figure 8. Opera displays a color picker when type is set to color.

Clicking the Other button below the swatches opens a full color picker that lets you select and store custom colors. The selected color is transmitted as a hexadecimal color value when the form is submitted.

What happens in older browsers

As mentioned earlier, the new HTML5 input elements have been designed to be backward compatible. So, if an older—or even relatively modern—browser doesn't recognize the new type attributes, it simply displays an ordinary text field. Figure 9 shows html5_input.html in IE 9.

Figure 9. IE 9 displays the new input types as ordinary text fields.
Figure 9. IE 9 displays the new input types as ordinary text fields.

The form remains perfectly usable in IE 9 and older browsers even though they have no support for HTML5 form elements.

Date- and time-related input

Six of the new input types are dedicated to date- and time-related values. Support for these input fields is still patchy. Currently, iOS, Android, Firefox 5, and IE 10 Preview 2 display ordinary text input fields. Chrome and Safari treat them like number spin boxes, increasing and decreasing the value depending on whether you click the up or down arrow. Opera and BlackBerry offer the most user-friendly support with calendar pop-ups. Figure 10 shows what happens when you put the focus in a date field in Opera 11.50. It displays a navigable calendar that defaults to the current date.

Figure 10. Opera makes it easy to insert dates from a pop-up calendar.
Figure 10. Opera makes it easy to insert dates from a pop-up calendar.

The latest versions of BlackBerry devices offer a similar experience. Figure 11 shows what happens when you tap a date field in a BlackBerry PlayBook.

Figure 11. The BlackBerry PlayBook displays a set of rolling barrels to choose the date.
Figure 11. The BlackBerry PlayBook displays a set of rolling barrels to choose the date.

In spite of their user-friendly date pickers, what comes as a surprise is the format of the date they enter into the form field. The date shown in Figure 11 is inserted as 2011-08-03—in other words, in the order year, month, and date. This is not an arbitrary decision, but is the format mandated by the World Wide Web Commission (W3C), which is responsible for drawing up the HTML5 specification.

The YYYY-MM-DD format has been chosen because it's the way the International Organization for Standardization (ISO) recommends that dates should be presented. Table 2 shows all date- and time-related input types in the HTML5 specification together with the required format.

Table 2. HTML5 date- and time-related input types

Type

Format

Description

date YYYY-MM-DD

Year (4 digits), month (2 digits), and date (2 digits), each value separated by hyphens.

datetime YYYY-MM-DDTHH:MMZ YYYY-MM-DDTHH:MM-07:00

UTC (Universal Coordinated Time) date and time. The date is expressed in the same format as date , followed by the letter T and the time in the 24-hour clock, optionally with the local offset from UTC. A zero offset is represented by the letter Z. The second example on the left shows the offset for Pacific Daylight Time (7 hours behind UTC).

datetime-local YYYY-MM-DDTHH:MM

The date and local time expressed in the same format as datetime , but without a UTC offset.

month YYYY-MM

The year (4 digits) and month (2 digits separated by a hyphen.

week YYYY-W00

The year (4 digits) followed by a hyphen, the letter W, and the week number (2 digits).

time HH:MM or HH:MM:SS.0000

Time expressed in the 24-hour clock with optional seconds and milliseconds. Hours, minutes, and seconds are separated by colons.

The W3C's choice of formats is intended to solve the vexed problem of differing date formats around the world. They work fine in a technical environment, but—with the exception of the time input type—are likely to confuse nontechnical users. Figure 12 shows actual examples of the official formats as rendered by Chrome 13.

Figure 12. The official date formats are likely to confuse many people.
Figure 12. The official date formats are likely to confuse many people.

Local customs regarding date formats are so deeply ingrained that I think the HTML5 date-related input types will find little practical application unless the specification is amended to permit alternative formats. Another possibility is that browsers could offer the option to display the date in a local format, but use the official format when the form is submitted.

In the meantime, I think the best approach is to provide separate text input fields or <select> menus for the month, date, and year. Alternatively, use a single text input field with a configurable JavaScript widget, such as the jQuery UI Datepicker. In Part 2 of this tutorial, I'll also show you how to use the pattern attribute with a text input field to enforce a specific date format in HTML5-compliant browsers.

Creating a slider input

The final new type attribute for the <input> tag is range , which creates a slider that allows the user to select a numeric value. Currently, this input type is supported by iOS, Safari, Chrome, and Opera. With the exception of Android, other browsers display an ordinary text input field. Unfortunately, in my experiments, Android completely ignores the range type, severely limiting its usefulness. However, it's an interesting input type, so I'll describe it in full.

According to the specification, the range input type is intended to be used when the exact value is not important. The reason for this becomes clear when you see a default slider in an HTML5-compliant browser. Figure 13 shows a slider in Opera (you can test it yourself in slider.html in the example files).

Figure 13. The range input type is normally displayed as a slider.
Figure 13. The range input type is normally displayed as a slider.

Although Opera displays a scale below the slider, other browsers don't, and there's no indication of the selected value. By default, the range type allows the user to select a value between 0 and 100, and is initially set to the halfway point—in other words, 50. Moving the slider in either direction increases or decreases the selected value in steps of 1.

On its own, the range input type is a very crude tool. However, with a little extra code, it becomes much more versatile. By setting the min, max, and step attributes, you can change the default range and incremental value (only whole numbers can be used). For example, the following HTML markup sets a range of 0–25 in steps of 5 (0, 5, 10, and so on):

<input type="range" name="rating" id="rating" min="0" max="25" step="5">

To set the initial value to zero, just add the value attribute like this:

<input type="range" name="rating" id="rating" min="0" max="25" step="5" value="0">

As Figure 14 shows, the slider is automatically set to the far left of the track, and Opera adjusts the scale to indicate the new range of selectable values (the code is in slider2.html in the example files).

Figure 14. Explicitly setting the value changes the initial position of the slider.
Figure 14. Explicitly setting the value changes the initial position of the slider.

Even though Chrome and Safari don't display a scale, if you test slider2.html in either of those browsers, you'll see that the slider stops only at positions roughly equivalent to 0, 5, 10, and so on. Still, it would be much better to show users what value they have selected. You can do so with the HTML5 <output> tag and some very simple JavaScript, as described in the next section.

Displaying the slider's value

The following instructions show how to display the value selected by an HTML5 range input element.

  1. Open slider2.html in the example files. The HTML markup for the form looks like this:
<form method="post" name="form1"> <p> <label for="rating">Rating:</label> <input type="range" name="rating" id="rating" min="0" max="25" step="5" value="0"> </p> </form>
  1. In Code view, position the insertion point immediately after the <input> tag and add an opening and closing pair of <output> tags like this (if you're using Dreamweaver CS5.5, code hints will autocomplete the tags):
<input type="range" name="rating" id="rating" min="0" max="25" step="5" value="0"><output></output>
  1. In the opening <output> tag, give the element a unique name, such as display_rate:
<output name="display_rate"></output>
  1. Link the <output> and <input> elements using the for attribute and setting its value to the <input> element's ID like this:
<output name="display_rate" for="rating"></output>
  1. To display the value selected by the slider, you need to add an onchange handler to the slider. Add the following code inside the <input> tag:
onchange="display_rate.value=this.value"

In JavaScript, this represents the target of the current event. So, whenever the slider is moved, this.value contains the slider's selected value. Because the name of the <output> element is display_rate, this code sets the value of the <output> element to the same value as the slider.

The complete code for the <input> and <output> elements should now look like this (the code is also in slider_output.html in the example files):

<input type="range" name="rating" id="rating" min="0" max="25" step="5" value="0" onchange="display_rate.value=this.value"><output name="display_rate" for="rating"></output>
  1. Save the page, and load it into a browser that supports the range input type (currently Chrome, Safari, or Opera). The <output> element doesn't have an initial value, so the slider should look the same as Figure 14.
  2. Move the slider. The selected value should appear alongside, as shown in Figure 15.
Figure 15. The value of the <output> element updates when the slider is moved.
Figure 15. The value of the <output> element updates when the slider is moved.

Note: According to the HTML5 specification, the default value of an <output> element must initially be an empty string—in other words, nothing. To change the default, you need to use JavaScript to set the element's defaultValue property when the page loads. This is currently supported only by Chrome and Safari. In practice, current browsers allow you to set the initial value by inserting a number between the opening and closing <output> tags. The number updates automatically when the slider is moved. However, this has the unfortunate side effect of displaying an unchanging value alongside the text field of the range input element.

Using a datalist to display options for text input

A really useful addition to HTML5 forms is the <datalist> element, which is currently supported only by Opera. It associates a set of predefined options with a text input field, allowing you to create an editable <select> menu. Figure 16 shows a simple example of a datalist in Opera.

Figure 16. A datalist offers suggestions for a text input field.
Figure 16. A datalist offers suggestions for a text input field.

When the focus is in the text field, the datalist displays a set of options for the user to choose from. If one is selected, it's entered in the field. However, the user is free to enter a completely different value. For example, Princess Leia could type "Princess" in the Title field rather than settling for plain Ms.

The HTML markup for a datalist is very simple. The example shown in Figure 16 looks like this (it's also in datalist.html in the example files):

<input type="text" name="title" id="title" list="titlelist"> <datalist id="titlelist"> <option value="Mr."> <option value="Mrs."> <option value="Ms."> </datalist>

You associate a text input field with a datalist by adding the list attribute to the <input> tag and setting its value to the ID of the <datalist> element—in this case, titlelist.

The <datalist> element serves as a wrapper for a set of <option> tags, which you probably recognize from <select> menus. An important difference is that a datalist requires the value attribute to be present in the <option> tag. Unlike a <select> menu, <datalist> won't display values nested between opening and closing tags. For example, the following won't work in a <datalist>:

<option>Mr.</option>

It must be like this:

<option value="Mr.">

Although the <datalist> element isn't yet widely supported, you can safely use it in existing forms. Browsers that don't recognize it simply display the ordinary text input field. But as soon as browser support catches up, visitors to your sites benefit from the list of suggested options.

Further improvements to forms

That concludes Part 1 of this overview of HTML5 forms, describing the 13 new input types and the <datalist> element. In Part 2, you'll learn about the new form attributes, such as autocomplete, autofocus, and required.

Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

More Like This

  • What's new in Dreamweaver CS5.5
  • Introduction to media queries – Part 1: What are media queries?
  • Packaging widgets with the Adobe Widget Browser
  • Applying design to Spry widgets
  • Integrating Flash content with the HTML environment
  • Introduction to media queries – Part 2: Building a responsive design
  • Responsive design with jQuery marquee
  • Understanding HTML5 semantics – Part 3: Changed and absent elements
  • Dreamweaver CS5 Missing Manual excerpts: Behaviors, site management, and templates
  • Understanding HTML5 semantics – Part 1: New elements

Tutorials and samples

Tutorials

  • Understanding HTML5 semantics: Changed and absent elements
  • Mobile app with PhoneGap: Submitting to the Apple App Store
  • PhoneGap and Dreamweaver: Releasing on iOS
  • Mobile app with PhoneGap: Creating a release build for Android

Samples

  • Responsive design with jQuery marquee
  • Customizable starter design for jQuery Mobile
  • Customizable starter design for HTML5 video
  • Customizable starter design for multiscreen development

Dreamweaver user forum

More
04/23/2012 Resolution/Compatibility/liquid layout
04/20/2012 using local/testing server with cs5 inserting images look fine in the split screen but do not show
04/18/2012 Ap Div help
04/23/2012 Updating

Dreamweaver Cookbook

More
11/07/2011 Simple social networking share buttons
09/20/2011 Registration form that will generate email for registrant to validate
08/21/2011 Spry Accordion - Vertical Text - Auto Start on Page Load - Mouse Over Pause
08/17/2011 Using cfdump anywhere you like

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement