How to Create Web Forms with HTML5

By Ed Tittel, Chris Minnick

HTML forms can present information to users, using text and images. Every form has the same basic structure. Which input elements you use depends upon the data you’re presenting and collecting.

The <form> element is a content and input container: It works much like the paragraph (<p>) element, which contains paragraph text, or like the division (<div>) element, which contains various types of sub-elements in a logical document section. Thus, all input elements associated with a single form are

  • Contained within a <form> element.

  • Processed by the same form handler.

A form handler is a program on the web server (or a simple mailto: URL) that manages the data a user sends to you through the form. A web browser can only gather information through forms; it doesn’t know what to do with the information after it has grabbed it. You must provide another mechanism to actually do something useful with data you collect in any form.

Attributes

You always use these two key attributes with the <form> tag:

  • action: The URL for the form handler

  • method: How you want form data to be sent to the form handler

    Your form handler dictates which of the following values to use for method. (Your hosting or service provider probably has a document that describes how to invoke your local web server’s form handler, including those oh-so-necessary details — and probably some examples, too.)

    • get sends the form data to the form handler on the URL.

    • post sends the form data in the HyperText Transfer Protocol (HTTP) header.

Webmonkey reviews the difference between get and post in its “Add HTML Forms to Your Site” article. You can also find a great discussion of HTML5 forms markup on the MSDN Magazine site.

Markup

The markup in this listing creates a form that uses the post method to send user-entered information to a form handler (guestbook.php) to be processed on the web server.

<!DOCTYPE html>
<html>
<head>
    <title>Forms</title>
    <meta charset="UTF-8" />
</head>
<body>
    <form action="bin/guestbook.php" method="post">
    <!-- form input elements go here →
    </form>
</body>
</html>

The value of the action attribute is a URL, so you can use absolute or relative URLs to point to a form handler on your server.