7
Working with Forms in HTML
In This Chapter
Using forms in your web pages
Creating forms
Working with form data
Designing easy-to-use forms
Making forms easy with a form framework
Most of the HTML you write helps you display content and information for your users. Sometimes, however, you want a web page to gather information from users instead of giving static information to them. HTML form markup elements give you a healthy collection of tags and attributes for creating forms to collect information from visitors to your site.
This chapter covers the many uses for forms. It also shows you how to use form markup tags to solicit information from your users, reviews your options for working with data you receive, and gives you tips on creating easy-to-use forms that help users provide the information you’re looking for.
Exploring Types of Web Forms
The web contains millions of forms, and every form is driven by the same set of markup tags. Web forms can be short or long, simple or complex, with myriad uses. But forms all fall into one of two broad categories:
Search forms that let users search a site or the entire web
Data collection forms that provide information for online shopping, technical support, site preferences, personalization, and more
Search forms
Search forms help you give visitors information.
The following search forms are from the friendly folks at the Internal Revenue Service (IRS). The difference between these search forms is the data the IRS site needs from you for its search:
The IRS forms and publications search page (shown in Figure 7-1) is a simple, multifaceted search form featuring current IRS documents to help visitors search for tax forms and publications. This type of page can pinpoint relevant responses for searches by document number or title. Visitors can
• Choose the best option to meet their search criteria.
• Look at all relevant options.
There’s a whole list of File Fillable Forms that permit online filing for most of the common IRS tax forms, including Form 1040ES (estimated tax), Form 1040A (and all the related schedules, of which there are about two dozen), and many more.
You can use the Online Payment Agreement (OPA) form to set up a payment plan with the IRS. It’s a two-parter where you pick from a number of radio buttons to describe your status and situation in the first part, and then provide your taxpayer ID, date of birth, and so forth in the second part.
Figure 7-1: The IRS forms search page offers access to forms and related publications.
Data collection forms
Data collection forms receive information you want to process or save. When you create a form that collects information, the information you need is what drives the structure and complexity of the form:
Just a little: If you need just a little information, the form may be short and (relatively) sweet.
Example: The Library of Congress (LoC) uses a form to collect information from teachers to subscribe to a free electronic newsletter, as shown in Figure 7-2. The LoC doesn’t need much information to set up the subscription, so the form is short and simple.
Figure 7-2: A free subscription form collects basic information.
Lots: If you need a lot of information, your form may be several pages long.
Example: RateGenius uses long and detailed forms to gather the information it needs to help customers refinance a vehicle loan. The page in Figure 7-3 shows just the first two of numerous panes that a visitor must fill out to provide all the necessary information.
Figure 7-3: Some sites use many detailed forms to collect necessary data.
Creating Forms
HTML forms can present information to users, using text and images. But it can also proffer various types of other methods of presenting information, including the following:
Text input fields, including in-line, single line, or multiple lines
Data selection tools, such as radio buttons (which let you pick one option from a group)
Pick lists, which let you fill in a value from a predefined set of options
Check boxes, which enable you to pick zero, one, or more values from a predefined set of inputs
All in all, HTML form markup tags and attributes help you
Define the overall form structure.
Tell the web browser how to handle form data.
Create input objects, such as text fields and drop-down lists.
Structure
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.
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.
Markup
The markup in Listing 7-1 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.
Listing 7-1: A Simple Form Processed by a Form Handler
<!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>
Input tags
The tags you use to solicit input from your site visitors make up the bulk of any form. HTML supports a variety of input options, from text fields to radio buttons and from files to images.
Every input control associates some value with a name:
When you create the control, you give it a name.
The control sends back a value based on what the user does in the form.
For example, if you create a text field that collects a user's first name, you might name the field firstname
. When the user types her first name in the field and submits the form, the value associated with firstname
is whatever name the user typed in the field.
The <input>
element (and by extension, the empty <input ... >
tag) is the major player when it comes to using HTML forms to solicit user input. Inside the <input>
element is where you define the kinds of input you want to collect, and how you package and present the input fields and cues you present to users so they can give you what you're asking for.
Input fields
You can use a variety of input field types in your forms, such as text
, password
, radio
(button), checkbox
, hidden
, search
, tel
(telephone number), url
, email
(address), datetime
, date
, month
, week
, time
, datetime-local
, number
, range
(sets a range of numeric values), color
, and more. Not all fields require values for name and type attributes (for example, text box or password fields), but it's a good idea to provide users with explanatory labels and examples of input data any time they might have questions about formats — such as when pondering whether to include dashes or spaces in credit card numbers. Check boxes and radio buttons, on the other hand, require such information so they can be properly labeled when the browser shows users what selections are available.
We discuss these two types of input fields in the upcoming section, “Check boxes and radio buttons.”
Text fields
Text fields are single-line fields into which users type information. When you need to offer the user the opportunity to fill in more than one line, you use a text box, as we discuss in the upcoming section, “Multiline text boxes.”
Here’s how to create a single-line text field:
1. Define the input type as a text field by using the <input />
element with the type
attribute set to text
.
<input type="text">
2. Then use the name
attribute to give the input field a name.
<input type="text" name="firstname">
The user supplies the value when she types in the field.
The following markup creates two text input fields, one for a first name and one for a last name:
<form action="bin/guestbook.php" method="post">
<ul style="list-style-type: none;">
<li>First Name: <input type="text" name="firstname"></li>
<li>Last Name: <input type="text" name="lastname"></li>
</ul>
</form>
You must use HTML block and inline elements to format the appearance of your form and also to supply the necessary text. Figure 7-4 shows how a browser displays this kind of HTML. (To see the markup that produced this figure, visit www.dummieshtml.com/html5cafe/ch07/07fig04.html
.)
Figure 7-4: Text entry fields in a form.
You can control the size of a text field with these attributes:
size
: The length (in characters) of the text field
maxlength
: The maximum number of characters the user can type into the field
The following markup creates a form that sets both fields to a size
of 30 (characters long) and a maxlength
of 25 (characters long). Even though each field will be about 30 characters long, a user can type only 25 characters into each field, as shown in Figure 7-5. (Setting the size
attribute greater than maxlength
ensures that the text field will always have some white space between the user input and the end of the field box on display; you don't have to do this yourself, but we find it visually pleasing.)
<form action="bin/guestbook.php" method="post">
<ul style="list-style-type: none;">
<li>First Name: <input type="text" name="firstname" size="30"
maxlength="25"></li>
<li>Last Name: <input type="text" name="lastname" size="30"
maxlength="25"></li>
</ul>
</form>
Figure 7-5: You can specify the length and maximum number of characters for a text field.
Password fields
A password field is a special text field that doesn’t display what the user types. Each keystroke is represented on the screen by a placeholder character, such as an asterisk or a bullet, so that someone looking over the user’s shoulder can’t see what they type.
You create a password field by using the <input>
element with the type
attribute set to password
, as follows:
<form action="bin/guestbook.php" method="post">
<ul style="list-style-type: none;">
<li>First Name: <input type="text" name="firstname" size="30"
maxlength="25"></li>
<li>Last Name: <input type="text" name="lastname" size="30"
maxlength="25"></li>
<li>Password: <input type="password" name="psswd" size="30"
maxlength="25"></li>
</ul>
</form>
Password fields are programmed like text fields.
Figure 7-6 shows how a browser replaces what you type with bullets. Note: Depending on the browser’s default settings, some browsers replace the text with asterisks or some other character.
Figure 7-6: Password fields mask the text a user enters.
Check boxes and radio buttons
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).
To create radio buttons and check boxes, take these steps:
1. Use the <input>
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.
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 Figure 7-7.
Figure 7-7: Radio and text buttons let users select from a list of predefined options.
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 <input>
element you want selected in advance.
Hidden fields
A hidden field lets you collect name and value information that the user can’t see along with the rest of the form data. Hidden fields are useful for keeping track of information associated with the form, such as its version or name.
To create a hidden field, here’s what you do:
1. Use the <input>
element with its type
attribute set to hidden
.
2. Supply the name and value pair you want to send to the form handler.
Here’s an example of markup for a hidden field:
<form action="bin/guestbook.php" method="post">
<input type="hidden" name="e-mail" value="[email protected]">
<ul style="list-style-type: none;">
<li>First Name: <input type="text" name="firstname" size="30"
maxlength="25"></li>
<li>Last Name: <input type="text" name="lastname" size="30"
maxlength="25"></li>
<li>Password: <input type="password" name="psswd" size="30"
maxlength="25"></li>
</ul>
</form>
File upload fields
A form can receive documents and other files, such as images, from users. When a user submits the form, the browser grabs a copy of the file and sends it with the other form data. To create a file upload field, this is what you do:
1. Use the <input>
element with the type
attribute set to file
.
The file itself is the form field value.
2. Use the name
attribute to give the control a name.
Here’s an example of markup for a file upload field:
<form action="bin/guestbook.php" method="post">
<p>Please submit your resume in Microsoft Word or plain text format:<br>
<input type="file" name="resume">
</p>
</form>
Browsers render a file upload field with a Browse button (or a button similarly named) that allows a user to navigate a local hard drive and select a file to send, as shown in Figure 7-8.
Figure 7-8: A file upload field rendered as a Choose File button.
Virus-scanning software
Restrictions on file size
Restrictions on file type
Drop-down list fields
Drop-down lists are a great way to give users lots of options in a small amount of screen space. You use two tags to create a drop-down list:
<select>
creates the list.
Use a name
attribute with the <select>
element to name your list.
A collection of <option>
elements identifies individual list options.
The value
attribute assigns a unique value for each <option>
element.
Here’s a markup example for a drop-down list:
<form action="bin/guestbook.php" method="post">
<p>What is your favorite food?</p>
<select name="food">
<option value="pizza">Pizza</option>
<option value="icecream">Ice Cream</option>
<option value="eggsham">Green Eggs and Ham</option>
</select>
</form>
The browser turns this markup into a drop-down list with three items, as shown in Figure 7-9.
Figure 7-9: A drop-down list.
If you want your users to be able to choose more than one option (by holding down the Ctrl [Windows] or [Mac] key while clicking options in the list), add the multiple
attribute to the <select>
tag. The value of multiple
is multiple
.
If you give a stand-alone attribute a value, that value must be the same as the name for the attribute itself (that is, both multiple
and multiple="multiple"
are legal).
By default, the browser displays only one option until the user clicks the drop-down menu arrow to display the rest of the list. Use the size
attribute with the <select>
tag to specify how many options to show.
If you specify fewer than the total number of options, the browser includes a scroll bar with the drop-down list.
You can specify that one of the options in the drop-down list be already selected when the browser loads the page, just as you can specify a check box or radio button to be selected. Simply add the selected
attribute for the <option>
tag you want as the default. Use this when one choice is very likely, knowing that users can override your default selection quickly and easily.
Multiline text boxes
If a single-line text field doesn’t offer enough room for a response, create a text box instead of a text field:
The <textarea>
element defines the box and its parameters.
The rows
attribute specifies the height of the box in rows based on the font in the text box.
The cols
attribute specifies the width of the box in columns based on the font in the text box.
The text that the user types into the box provides the value, so you need only give the box a name with the name
attribute:
<form action="bin/guestbook.php" method="post">
<p> Please include any comments here.</p>
<textarea rows="10" cols="40" name="comments">
...comments here...
</textarea>
</form>
Figure 7-10: A text box.
Submit and Reset buttons
Submit and Reset buttons help the user tell the browser what to do with the form. You can create buttons to either submit or reset your form, using the <input>
element with the following type
and value
attributes:
Submit: Visitors have to tell a browser when they’re done with a form and want to send the contents. You create a button to submit the form to you by using the following markup:
<input type="submit" value="Submit">
You don't use the name
attribute for the Submit and Reset buttons. Instead, you use the value
attribute to specify how the browser labels the buttons for display.
Reset: Visitors need to clear the form if they want to start all over again or decide not to fill it out. You create a button to reset (clear) the form by using the following markup:
<input type="reset" value="Clear">
Listing 7-2 shows an example of markup to create Submit and Reset buttons named Send and Clear, respectively.
Listing 7-2: A Complete Multipart Form
<!DOCTYPE html>
<html>
<head>
<title>Basic Form Markup</title>
<meta charset="UFT-8" />
<style type="text/css">
h1 {background-color: silver;
color: black;
font-size: 1.2em;
font-family: Arial, Verdana, sans-serif;}
hr {color: blue;
width: thick;}
body {font-size: 12pt;
color: brown;
font-family: Tahoma, Bodoni, sans-serif;
line-height: 0.8em;}
</style>
</head>
<body>
<h1>Multi-Part Form</h1>
<hr />
<div>
<form action="bin/guestbook.php" method="post">
<h1>Name and Password</h1>
<p>First Name: <input type="text" name="firstname" size="30"
maxlength="25"></p>
<p>Last Name: <input type="text" name="lastname" size="30"
maxlength="25"></p>
<p>Password: <input type="password" name="psswd" size="30"
maxlength="25"></p>
<h1>Favorite Foods</h1>
<p>What are some of your favorite foods?</p>
<p><input type="checkbox" name="food" value="pizza"
checked="checked">Pizza</p>
<p><input type="checkbox" name="food" value="icecream">
Ice Cream</p>
<p><input type="checkbox" name="food" value="eggsham">
Green Eggs and Ham</p>
<h1>Gender Information</h1>
<p>What is your gender?</p>
<p><input type="radio" name="gender" value="male">Male</p>
<p><input type="radio" name="gender" value="female">Female</p>
<p style="line-height: 2em; margin: 2em;">
<input type="submit" value="Send">
<input type="reset" value="Clear">
</p>
</form>
</div>
<hr>
</body>
</html>
Figure 7-11 shows how a browser renders these buttons in a form.
Form validation
No matter how brilliant your site’s visitors may be, there’s always a chance that they’ll enter data you aren’t expecting or perhaps leave some important field unfilled. JavaScript to the rescue!
Figure 7-11: Submit and Reset buttons are labeled as Send and Clear.
Form validation is the process of checking data the user enters before it’s put into your database. You can check the data either with local JavaScript or PHP scripts on your server.
JavaScript
You can validate entries in JavaScript before data goes to the server. This means that visitors don’t wait for your server to check the data. They’re told quickly (before they click Submit, if you want) if there’s a problem.
www.w3schools.com/js/default.asp
www.quirksmode.org/js/forms.html
www.webmonkey.com/2010/02/javascript_tutorial
PHP
You need to validate your form data on the server side because users can surf with JavaScript turned off. (They’ll have a slower validation process.) Find out more about PHP at these sites:
www.4guysfromrolla.com/webtech/LearnMore/Validation.asp
Processing Data
Getting form data is really only half the form battle. You create form elements to get data from users, but then you have to do something with that data. Of course, your form and your data are unique every time, so no single, generic form handler can manage the data for every form. Before you can find (or write) a program that handles your form data, you must know what you want to do with it. For example:
If you just want to receive comments from a web form by e-mail, you might need only a simple mailto:
URL.
If a form gathers information from users to display in a guest book, you
• Add the data to a text file or a small database that holds the entries.
• Create a web page that displays the guest-book entries.
If you want to use a shopping cart, you need programs and a database that can handle inventory, customer order information, shipping data, and cost calculations.
Processing forms on your pages
Typically, form data is processed in some way or another by some kind of program running on a web server. It might be a PHP script written in some programming language such as Perl, Java, or AppleScript, or a different handler program written using PHP, Apache, Java Server Pages (JSP), ASP, or other programs that run on web servers to process user input. These programs make data from your form useful by
Putting it into a database or sharing it with some other kind of program.
Creating customized HTML based on the data.
Writing the data to a flat file.
Flat file is computer-geek speak for a plain, unadorned text file, or one that uses commas or tab characters on individual lines of text to separate field values (also known as CSV for comma-separated values or TSV for tab-separated values).
You don’t have to be a programmer to make the most of forms. Many ISPs support (and provide) scripts for processing common forms, such as guest books, comment forms, and even shopping carts. Your ISP may give you
All the information you need to get an input-processing program up and running
HTML to include in your pages so they can interact with that program
Several online script repositories provide free scripts that you can download and use along with your forms. Many of these also come with some generic HTML you can dress up and tweak to fit your website. You simply drop the program that processes the form into the folder on your site that holds programs (sometimes called php-bin
, often something else), add the HTML to your page, and you're good to go. Some choice places on the web to find scripts you can download and put to work immediately are
Matt's Script archive: www.scriptarchive.com/nms.html
The PHP Resource Index: http://php.resourceindex.com
The Developer.com Network: www.developer.com
Handling forms is beyond the scope of this book, but you can find out more about them from these friendly For Dummies titles:
PHP and MySQL For Dummies, 4th Edition (2009)
www.dummies.com/store/product/PHP-and-MySQL-For-Dummies-4th-Edition.productCd-0470527587.html
HTML5 Programming with JavaScript For Dummies (2013)
Designing User-Friendly Forms
Designing useful forms is a different undertaking from designing easy-to-use forms. Your form may gather the data that you need, but if your form is difficult for visitors to use, they may abandon it before they’re done.
Provide textual cues for all your forms. Be clear about the information you want and the format you need.
For example, tell users details such as whether
• Dates must be entered as mm/dd/yy
(versus mm/dd/yyyy
).
• The number of characters a field can take is limited.
As we explain earlier in this chapter, you can limit character by using the maxlength
attribute.
Use field width and character limits to provide visual clues. For example, if users should enter a credit card number as xxxx-xxxx-xxxx-xxxx, consider creating four text fields — one for each part of the number.
Group similar fields. A logical grouping of fields makes filling out a form easier. It’s confusing if you ask for the visitor’s first name, then birthday, and then last name.
Break long forms into easy-to-manage sections. Forms in short chunks are less intimidating and more likely to be completed.
Major online retailers (such as Amazon.com — www.amazon.com
) use this method to get the detail they need for orders without making the process too painful.
Mark required fields clearly. If some parts of your form can’t be left blank when users submit the form, mark those fields clearly.
You can identify required fields by
• Making them bold
• Using a different color
• Placing an asterisk beside them
Write helpful, friendly error messages. Make sure your form validation feedback makes sense to site visitors (check them with a group of testers just to make sure). Nothing turns visitors away like cryptic unhelpful message. (“Type 42 error” may mean something to a programmer, but not to anybody else.)
Tell users what kind of information they need for the form. If users need any information in their hands before they fill out your form, a form gateway page can detail everything users should have before they start filling out the form.
Other Noteworthy Forms-Related Markup
Table 7-1 lists other forms-related HTML markup attributes that you might find in HTML files.
Here’s a key for the Value Types Column in Table 7-1:
CDATA: SGML character data type permits all keyboard characters to be used.
CS Media Types: Case-sensitive type names such as “text/html” “image/gif” or “text/css.”
Character set encodings: Usually UTF-8, ISO-LATIN-1, or ISO-8859-1. For a more complete list, see www.w3schools.com/TAGS/ref_charactersets.asp
.
MIME: Abbreviation for Multi-part Internet Mail Extensions, a standard method to encode various document and data types for e-mail attachments and for HTTP. For more info, see http://en.wikipedia.org/wiki/MIME
.
Form Frameworks
Form frameworks basically put all the building blocks for building, validating, and processing forms data together into a single coherent collection of tools and code. When you know how to use a framework, it’s trivial to build complex robust forms of your own — at least, as long as that framework is available on your web server.
Wufoo (http://wufoo.com
): Wufoo is an HTML form builder that helps you create contact forms, online surveys, and invitations so you can collect data, registrations, and online payments you need without writing a single line of code. Quick and easy!
jQuery Validation Plugins (http://docs.jquery.com/Plugins/Validation
): Even though jQuery makes it easy to write your own validation plugins, there are still a lot of subtleties you must worry about. For example, you need a standard library of validation methods. (Think of e-mails, URLs, and credit card numbers.) You need to place error messages into web documents and then show and hide them when appropriate. You want to react to more than just a submit event, like keyup
or blur
. You may need different ways to specify validation rules, based on the server-side environment in use for a particular project. And after all, you don't want to reinvent the wheel, do you?
Validatious (http://validatious.org/learn/examples
): Validatious offers easy form validation with unobtrusive JavaScript support, using a predefined CSS class named validate
. This makes validations simply a matter of adding validator names to form elements, such as input
, select
, textarea
, and so forth. It's not a complete forms framework but does make the validation part — often the trickiest for newbies and professionals alike — smooth and straightforward.
In addition, many web-oriented development environments (such as Visual Studio, Web Expressions, ASP.NET, and so forth) also include extensive form design and processing components. These work like frameworks, too, but generally require you to work within their overall environments to take advantage of their often awesome capabilities.
3.14.128.105