To this point, pretty much everything in this book has focused on getting information out to others. But you can also use your web pages to gather information from the people who read them.
Web forms enable you to receive feedback, orders, or other information from the users who visit your web pages. If you’ve ever used a search engine such as Google, Yahoo!, or Bing, you’re familiar with HTML forms—those single field entry forms with one button that, when pressed, give you all the information you are looking for and then some. Product order forms are also an extremely popular use of forms; if you’ve ordered anything from Amazon.com or purchased something from an eBay seller, you’ve used forms. In this chapter, you learn how to create your own forms, but you learn only how to create the front-end of those forms. Working with the back-end of forms requires the knowledge of a programming language and is beyond the scope of this book. However, in some instances JavaScript can play a role in form processing, such as rudimentary form content delivery and validation.
An HTML form is part of a web page that includes areas where users can enter information to be sent back to you, sent to another email address that you specify, sent to a database that you manage, or sent to another system altogether such as a third-party management system for your forms such as Salesforce.com.
Before you learn the HTML tags that are used to make your own forms, you should at least conceptually understand how the information from those forms makes its way back to you. The actual behind-the-scenes (the server-side or back-end) process requires knowledge of at least one programming language or at least the ability to follow specific instructions when using someone else’s server-side script to handle the form input. At that point in the process, you should either work with someone who has the technical knowledge, or you should learn the basics on your own. Simple form-processing is not difficult at all and it is likely that your web-hosting provider has several back-end scripts that you can use with minimal customization.
Note
PHP is the most popular server-side programming language; it’s supported by any web-hosting provider worth its salt. You can learn more about PHP at http://www.php.net/ or you can just dive right in to learning this programming language (plus database interactivity) from the ground up in PHP, MySQL and Apache All in One (ISBN: 067232976X). Although several other books on PHP and related technologies are available, I am partial to this one because I wrote it. It is geared toward absolute beginners with PHP or any other programming language.
Forms include a button for the user to submit the form; that button can be an image that you create yourself or a standard HTML form button that is created when a form <input>
tag is created and given a type
value of submit
. When someone clicks a form submission button, all the information typed in the form is sent to a URL that you specify in the action
attribute of the <form>
tag. That URL should point to a specific script that will process your form, sending the form contents via email or performing another step in an interactive process (such as requesting results from a search engine or placing items in an online shopping cart).
After you start thinking about doing more with form content than simply emailing results to yourself, additional technical knowledge is required. For example, if you want to create an online store that accepts credit cards and processes transactions, there are some well-established practices for doing so, all geared toward ensuring the security of your customers’ data. That is not an operation that you’ll want to enter into lightly; you’ll need more knowledge than this book provides.
Note
There is a way to send form data without a server-side script, and you’ll learn about that method—which uses a mailto link in the action
attribute of the <form>
—later in this chapter. But as you try that, be aware that it can produce inconsistent results; individual web browsers, as well as personal security settings, can cause that action to respond differently than what you intended.
Before you put a form online, you should look in the user guide for your web-hosting provider and see what they offer in the way of form-processing scripts. You are likely to find a readily available Perl or PHP script that you can use with only minimal configuration.
Every form must begin with a <form>
tag, which can be located anywhere in the body of the HTML document. The <form>
tag normally has three attributes, name
, method
and action
:
<form name="form1" method="post" action="/myprocessingscript.php">
The most common method
is post
, which sends the form entry results as a document. In some situations, you might need to use method="get"
, which submits the results as part of the URL header instead. For example, get
is sometimes used when submitting queries to search engines from a web form. Because you’re not yet an expert on forms, just use post
unless your web-hosting provider’s documentation tells you to do otherwise.
The action
attribute specifies the address to which to send the form data. You have two options here:
• You can type the location of a form-processing program or script on a web server and the form data will then be sent to that program.
• You can type mailto:
followed by your email address and the form data will be sent directly to you whenever someone fills out the form. However, this approach is completely dependent on the user’s computer being properly configured with an email client. People accessing your site from a public computer without an email client will be left out in the cold.
<form method="post" action="mailto:[email protected]">
Each form in your HTML page is represented in JavaScript by a form
object, which has the same name as the name
attribute in the <form>
tag you used to define it.
Alternatively, you can use the forms
array to refer to forms. This array includes an item for each form element, indexed starting with 0. For example, if the first form in a document has the name form1
, you can refer to it in one of two ways:
document.form1
document.forms[0]
Along with the elements, each form
object also has a list of properties, most of which are defined by the corresponding <form>
tag. You can also set these from within JavaScript. They include the following:
• action
is the form’s action
attribute, or the program to which the form data will be submitted.
• encoding
is the MIME
type of the form, specified with the enctype
attribute. In most cases, this is not needed (unless you are uploading a file with the form).
• length
is the number of elements in the form. You cannot change this property.
• method
is the method used to submit the form, either GET
or POST
. This determines the data format used to send the form result to a CGI script and does not affect JavaScript.
• target
specifies the window in which the result of the form (from the CGI script) will be displayed. Normally, this is done in the main window, replacing the form itself, but you can use this attribute to work with pop-up windows or frames.
The form created in Listing 26.1 and shown in Figure 26.1 includes just about every type of user input component you can currently use on HTML forms. Refer to this listing and figure as you read the following explanations of each type of input element.
Figure 26.1 The code shown in Listing 26.1 uses nearly every type of HTML form input element.
Listing 26.1 A Form with Various User-Input Components
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Guest Book</title>
<style type="text/css">
.formlabel {
font-weight:bold;
width: 250px;
margin-bottom: 12px;
float: left;
text-align: left;
clear: left;
}
.formfield {
font-weight:normal;
margin-bottom: 12px;
float: left;
text-align: left;
}
input, textarea, select {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>My Guest Book</h1>
<p>Please sign my guest book. Thanks!</p>
<form name="gbForm" method="post" action="URL_to_script">
<div class="formlabel">What is your name?</div>
<div class="formfield"><input type="text" name="name"
size="50" /></div>
<div class="formlabel">What is your e-mail address?</div>
<div class="formfield"><input type="text" name="email"
size="50" /></div>
<div class="formlabel">Please check all that apply:</div>
<div class="formfield">
<input type="checkbox" name="website_response[]" value="I
really like your Web site." />I really like your Web site.<br />
<input type="checkbox" name="website_response[]" value="One
of the best sites I've seen." />One of the best sites I've
seen.<br />
<input type="checkbox" name="website_response[]" value="I sure
wish my site looked as good as yours." />I sure wish my site
looked as good as yours.<br />
<input type="checkbox" name="website_response[]" value="I have
no taste and I'm pretty dense, so your site didn't do much for
me." />I have no taste and I'm pretty dense, so your site
didn't do much for me.<br />
</div>
<div class="formlabel">Choose the one thing you love best about my
web site:</div>
<div class="formfield">
<input type="radio" name="lovebest" value="me" />That gorgeous
picture of you.<br />
<input type="radio" name="lovebest" value="cats" />All the
beautiful pictures of your cats.<br />
<input type="radio" name="lovebest" value="childhood" />The
inspiring recap of your suburban childhood.<br />
<input type="radio" name="lovebest" value="treasures" />The
detailed list of all your Elvis memorabilia.<br />
</div>
<div class="formlabel">If my web site were a book, how many copies
would it sell?</div>
<div class="formfield">
<select size="3" name="sales">
<option value="Millions, for sure." selected="selected">Millions,
for sure.</option>
<option value="100,000+ (would be Oprah's favorite)">100,000+
(would be Oprah's favorite)</option>
<option value="Thousands (an under-appreciated classic)">
Thousands (an under-appreciated classic)</option>
<option value="Very few: not banal enough for today's
public">Very few: not banal enough for today's
public.</option>
<option value="Sell? None. Everyone will download it
for free.">Sell? None. Everyone will download it for
free.</option>
</select>
</div>
<div class="formlabel">How can I improve my web site?</div>
<div class="formfield">
<select name="suggestion">
<option value="Couldn't be better." selected="selected">Couldn't
be better.</option>
<option value="More about the cats.">More about the
cats.</option>
<option value="More about the family.">More about the
family.</option>
<option value="More about Elvis.">More about Elvis.</option>
</select>
</div>
<div class="formlabel">Feel free to type more praise,
gift offers, etc. below:</div>
<div class="formfield">
<textarea name="comments" rows="4" cols="55"></textarea>
</div>
<div style="float:left;">
<input type="submit" value="Click Here to Submit" />
<input type="reset" value="Erase and Start Over" />
</div>
</form>
</body>
</html>
The code in Listing 26.1 uses a <form>
tag that contains quite a few <input />
tags. Each <input />
tag corresponds to a specific user input component, such as a check box or radio button. The input, select, and text area elements contain borders in the style sheet, so it is easy to see the outline of the elements in the form. Keep in mind that you can apply all sorts of CSS to those elements.
The next few sections dig into the <input />
and other form-related tags in detail.
To ask the user for a specific piece of information within a form, use the <input />
tag. This tag must fall between the <form>
and </form>
tags, but it can be anywhere on the page in relation to text, images, and other HTML tags. For example, to ask for someone’s name, you could type the following text followed immediately by an <input />
field:
<p>What's your name? <input type="text" size="50"
maxlength="100" name="user_name" /></p>
Tip
If you want the user to enter text without the text being displayed on the screen, you can use <input type="password" />
instead of <input type="text" />
. Asterisks (***
) are then displayed in place of the text the user types. The size
, maxlength
, and name
attributes work exactly the same for type="password"
as they do for type="text"
. Keep in mind that this technique of hiding a password provides only visual protection; there is no encryption or other protection associated with the password being transmitted.
The type
attribute indicates what type of form element to display—a simple, one-line text entry box in this case. (Each element type is discussed individually in this chapter.)
The size
attribute indicates approximately how many characters wide the text input box should be. If you are using a proportionally spaced font, the width of the input will vary depending on what the user enters. If the input is too long to fit in the box, most web browsers will automatically scroll the text to the left.
The maxlength
attribute determines the number of characters the user is allowed to type into the text box. If a user tries to type beyond the specified length, the extra characters won’t appear. You can specify a length that is longer, shorter, or the same as the physical size of the text box. The size
and maxlength
attributes are used only for type="text"
because other input types (check boxes, radio buttons, and so on) have fixed sizes.
No matter what type an input element is, you must give a name to the data it gathers. You can use any name you like for each input item, as long as each one on the form is different (except in the case of radio buttons and check boxes, which are discussed later in this chapter). When the form is processed by a back-end script, each data item is identified by name. This name becomes a variable, which is filled with a value. The value is either what the user typed in the form or the value associated with the element the user selected.
Note
Form-processing scripts are oversimplified here for the sake of explanation within the scope of this book. The exact appearance (or name) of the variables made available to your processing script depends on the programming language of that script. But conceptually, it’s valid to say that the name of the input element becomes the name of the variable and the value of the input element becomes that variable’s value on the back-end.
For example, if a user enters Jane Doe in the text box defined previously, a variable is sent to the form processing script; the variable is user_name
and the value of the variable is Jane Doe
. Form-processing scripts work with these types of variable names and values.
To use this (or other) text fields in JavaScript, remember that the text object uses the name
attribute; you would refer to the value of the field in the previous snippet as:
document.formname.user_name.value
Additional examples of name/value pairs are covered throughout this chapter.
Want to send certain data items to the server script that processes a form but don’t want the user to see those data items? Use an <input />
tag with a type="hidden"
attribute. This attribute has no effect on the display; it just adds any name and value you specify to the form results when they are submitted.
If you are using a form-processing script provided by your web-hosting provider, you might use this attribute to tell a script where to email the form results. For example, including the following code will email the results to [email protected]
after the form has been submitted:
<input type="hidden" name="mailto" value="[email protected]" />
You might sometimes see scripts using hidden input elements to carry additional data that might be useful when you receive the results of the form submission; some examples of hidden form fields include an email address and a subject for the email. If you are using a script provided by your web hosting provider, consult the documentation provided with that script for additional details about potential required hidden fields.
Various input controls are available for retrieving information from the user. You’ve already seen one text-entry option, and the next few sections introduce you to most of the remaining form-input options you can use to design forms.
The simplest input type is a check box, which appears as a small square. Users can click checkboxes to select or deselect one or more items in a group. For example, the checkboxes listed in Listing 26.1 display after a label that reads “Please check all that apply,” implying that the user could indeed check all that apply.
The HTML for the check boxes in Listing 26.1 shows that the value of the name
attribute is the same for all of them: website_response[]
.
<input type="checkbox" name="website_response[]" value="I
really like your Web site." />I really like your Web site.<br />
<input type="checkbox" name="website_response[]" value="One
of the best sites I've seen." />One of the best sites I've
seen.<br />
<input type="checkbox" name="website_response[]" value="I sure
wish my site looked as good as yours." />I sure wish my site
looked as good as yours.<br />
<input type="checkbox" name="website_response[]" value="I have
no taste and I'm pretty dense, so your site didn't do much for
me." />I have no taste and I'm pretty dense, so your site
didn't do much for me.<br />
The use of the brackets in the name
attribute ([]
) indicates to the processing script that a series of values will be placed into this one variable, instead of just one value (well, it might just be one value if the user only selects one check box). If a user selects the first check box, the text string “I really like your Web site.” will be placed in the website_response[]
bucket. If the user selects the third checkbox, the text string “I sure wish my site looked as good as yours.” will also be put into the website_response[]
bucket. The processing script will then work with that variable as an array of data rather just a single entry.
Tip
If you find that the label for an input element is displayed too close to the element, just add a space between the close of the <input />
tag and the start of the label text, like this:
<input type="checkbox" name="mini" /> Mini Piano Stool
However, you might see groups of check boxes that do use individual names for the variables in the group. For example, the following is another way of writing the check box group:
<input type="checkbox" name="liked_site" value="yes" /> I really like
your Web site.<br />
<input type="checkbox" name="best_site" value="yes" /> One of the best
Sites I've seen.<br />
<input type="checkbox" name="my_site_sucks" value="yes" />I sure wish my
site looked as good as yours.<br />
<input type="checkbox" name="am_dense" value="yes" />I have no taste and
I'm pretty dense, so your site didn't do much for me.<br />
In the previous check boxes, the variable name of the first check box is "liked_site"
and the value (if checked) is "yes"
.
If you want a check box to be checked by default when the form is rendered by the web browser, include the checked
attribute. For example, the following code creates two check boxes and the first is checked by default:
<input type="checkbox" name="website_response[]" value="I
really like your Web site." checked="checked" />I really like
your Web site.<br />
<input type="checkbox" name="website_response[]" value="One
of the best sites I've seen." />One of the best sites I've
seen.<br />
Caution
XHTML requires all attributes to have an equal sign followed by a value. This explains why checked="checked"
is used to indicate that a check box is checked (as opposed to just checked)
. This rule applies to all Boolean attributes (true
/false
, on
/off
, yes
/no
, and so on) that you might come across in HTML.
The check box labeled “I really like your site.” is checked by default in this example. The user would have to click the check box to indicate they had another opinion of your site. The check box marked “One of the best I’ve seen.” would be unchecked to begin with, so the user would have to click it to turn it on. Check boxes that are not selected do not appear in the form output at all.
If you want to handle values from the checkbox
object in JavaScript, the object has the following four properties:
• name
is the name of the check box and also the object name.
• value
is the “true” value for the check box—usually on
. This value is used by server-side programs to indicate whether the check box was checked. In JavaScript, you should use the checked
property instead.
• defaultChecked
is the default status of the check box, assigned by the checked
attribute in HTML.
• checked
is the current value. This is a Boolean value: true
for checked and false
for unchecked.
To manipulate the check box or use its value, you use the checked
property. For example, this statement turns on a check box called same_address
in a form named order
:
document.order.same.checked = true;
The check box has a single method: click()
. This method simulates a click on the box. It also has a single event, onClick
, which occurs whenever the check box is clicked. This happens whether the box was turned on or off, so you’ll need to examine the checked
property via JavaScript to see what action really happened.
Radio buttons, for which only one choice can be selected at a time, are almost as simple to implement as check boxes. The simplest use of a radio button is for yes/no questions or for voting when only one candidate can be selected.
To create a radio button, just use type="radio"
and give each option its own <input />
tag. Use the same name
for all the radio buttons in a group, but don’t use the []
that you used with the check box:
<input type="radio" name="vote" value="yes" checked="checked" /> Yes<br />
<input type="radio" name="vote" value="no" /> No <br/>
The value
can be any name or code you choose. If you include the checked
attribute, that button is selected by default. No more than one radio button with the same name
can be checked.
Note
Radio buttons are named for their similarity to the buttons on old pushbutton radios. Those buttons used a mechanical arrangement so that when you pushed one button in, the others popped out.
When designing your form and choosing between checkboxes and radio buttons, ask yourself, “Is the question being asked one that could be answered only one way?” If so, use a radio button.
As for scripting, radio buttons are similar to check boxes, except that an entire group of them shares a single name and a single object. You can refer to the following properties of the radio
object:
• name
is the name common to the radio buttons.
• length
is the number of radio buttons in the group.
To access the individual buttons in JavaScript, you treat the radio
object as an array. The buttons are indexed, starting with 0
. Each individual button has the following properties:
• value
is the value assigned to the button.
• defaultChecked
indicates the value of the checked
attribute and the default state of the button.
• checked
is the current state.
For example, you can check the first radio button in the radio1
group on the form1
form with this statement:
document.form1.radio1[0].checked = true;
However, if you do this, be sure you set the other values to false
as needed. This is not done automatically. You can use the click()
method to do both of these in one step.
Like a check box, radio buttons have a click()
method and an onClick
event handler. Each radio button can have a separate statement for this event.
Both scrolling lists and pull-down pick lists are created with the <select>
tag. You use this tag together with the <option>
tag, as the following example shows (taken from Listing 26.1):
<select size="3" name="sales">
<option value="Millions, for sure." selected="selected">Millions,
for sure.</option>
<option value="100,000+ (would be Oprah's favorite)">100,000+
(would be Oprah's favorite)</option>
<option value="Thousands (an under-appreciated classic)">Thousands
(an under-appreciated classic)</option>
<option value="Very few: not banal enough for today's public">Very
few: not banal enough for today's public.</option>
<option value="Sell? None. Everyone will download it for free.">Sell?
None. Everyone will download it for free.</option>
</select>
No HTML tags other than <option>
and </option>
should appear between the <select>
and </select>
tags.
Tip
If you leave out the size
attribute or specify size="1"
, the list creates a drop-down pick list. Pick lists don’t allow for multiple choices; they are logically equivalent to a group of radio buttons. The following example shows another way to choose yes or no for a question:
<select name="vote">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
Unlike the text
input type, the size
attribute here determines how many items show at once on the selection list. If size="2"
were used in the preceding code, only the first two options would be visible and a scrollbar would appear next to the list so the user could scroll down to see the third option.
Including the multiple
attribute enables users to select more than one option at a time; the selected
attribute makes an option initially selected by default. When the form is submitted, the text specified in the value
attribute for each option accompanies the selected option.
The object for selection lists is the select
object. The object itself has the following properties:
• name
is the name of the selection list.
• length
is the number of options in the list.
• options
is the array of options. Each selectable option has an entry in this array.
• selectedIndex
returns the index value of the currently selected item. You can use this to check the value easily. In a multiple-selection list, this indicates the first selected item.
The options
array has a single property of its own, length
, which indicates the number of selections. In addition, each item in the options
array has the following properties:
• index
is the index into the array.
• defaultSelected
indicates the state of the selected
attribute.
• selected
is the current state of the option. Setting this property to true
selects the option. The user can select multiple options if the multiple
attribute is included in the <select>
tag.
• name
is the value of the name
attribute. This is used by the server.
• text
is the text that is displayed in the option.
The select
object has two methods—blur()
and focus()
—which perform the same purposes as the corresponding methods for text
objects. The event handlers are onBlur
, onFocus
, and onChange
, also similar to other objects.
Note
You can change selection lists dynamically—for example, choosing a product in one list could control which options are available in another list. You can also add and delete options from the list.
Reading the value of a selected item is a two-step process. You first use the selectedIndex
property, and then use the value
property to find the value of the selected choice. Here’s an example:
ind = document.mvform.choice.selectedIndex;
val = document.mvform.choice.options[ind].value;
This uses the ind
variable to store the selected index, and then assigns the val
variable to the value of the selected choice. Things are a bit more complicated with a multiple selection; you have to test each option’s selected
attribute separately.
The <input type="text">
attribute mentioned earlier this chapter allows the user to enter only a single line of text. When you want to allow multiple lines of text in a single input item, use the <textarea>
and </textarea>
tags to create a text area instead of just a text field. Any text you include between these two tags is displayed as the default entry. Here’s an example:
<textarea name="comments" rows="4" cols="20">Your
message here.</textarea>
As you probably guessed, the rows
and cols
attributes control the number of rows and columns of text that fit in the input box. The cols
attribute is a little less exact than rows
and approximates the number of characters that fit in a row of text. Text area boxes do have a scrollbar, however, so the user can enter more text than what fits in the display area.
The text
and textarea
objects also have a few methods you can use:
• focus()
sets the focus to the field. This positions the cursor in the field and makes it the current field.
• blur()
is the opposite; it removes the focus from the field.
• select()
selects the text in the field, just as a user can do with the mouse. All of the text is selected; there is no way to select part of the text.
You can also use event handlers to detect when the value of a text field changes. The text
and textarea
objects support the following event handlers:
• The onFocus
event happens when the text field gains focus.
• The onBlur
event happens when the text field loses focus.
• The onChange
event happens when the user changes the text in the field and then moves out of it.
• The onSelect
event happens when the user selects some or all of the text in the field. Unfortunately, there’s no way to tell exactly which part of the text was selected. (If the text is selected with the select()
method described previously, this event is not triggered.)
If used, these event handlers should be included in the <input>
tag declaration. For example, the following is a text field including an onChange
event that displays an alert:
<input type="text" name="text1" onChange="window.alert('Changed.')," />
Forms typically include a button that submits the form data to a script on the server or invokes a JavaScript action. You can put any label you like on the submit button with the value
attribute:
<input type="submit" value="Place My Order Now!" />
A gray button will be sized to fit the label you put in the value
attribute. When the user clicks it, all data items on the form are sent to the email address or script specified in the form’s action
attribute.
You can also include a Reset button that clears all entries on the form so users can start over if they change their minds or make mistakes. Use the following:
<input type="reset" value="Clear This Form and Start Over" />
If the standard Submit and Reset buttons look a little bland to you, remember that you can style them using CSS. If that’s not good enough, you’ll be glad to know that there is an easy way to substitute your own graphics for these buttons. To use an image of your choice for a Submit button, use the following:
<input type="image" src="button.gif" alt="Order Now!" />
The button.gif
image will display on the page and the form will be submitted when a user clicks the button.gif
image. You can also include any attributes normally used with the <img />
tag, such as alt
and style
.
The form element also includes a generic button type. When using type="button"
in the <input />
tag, you will get a button that performs no action on its own but can have an action assigned to it using a JavaScript event handler.
The form
object has two methods: submit()
and reset()
. You can use these methods to submit the data or reset the form yourself, without requiring the user to press a button. One reason for this is to submit the form when the user clicks an image or performs another action that would not usually submit the form.
Caution
If you use the submit()
method to send data to a server or by email, most browsers will prompt the user to verify that he wants to submit the information. There’s no way to do this behind the user’s back.
The form
object has two event handlers, onSubmit
and onReset
. You can specify a group of JavaScript statements or a function call for these events within the <form>
tag that defines the form.
If you specify a statement or a function for the onSubmit
event, the statement is called before the data is submitted to the server-side script. You can prevent the submission from happening by returning a value of false
from the onSubmit
event handler. If the statement returns true
, the data will be submitted. In the same fashion, you can prevent a Reset button from working with an onReset
event handler.
The most important property of the form
object is the elements
array, which contains an object for each of the form elements. You can refer to an element by its own name or by its index in the array. For example, the following two expressions both refer to the first element in the form shown in Listing 26.1:
document.gbForm.elements[0]
document.gbForm.name
Note
Both forms and elements can be referred to by their own names or as indices in the forms
and elements
arrays. For clarity, the examples in this chapter use individual form and element names rather than array references. You’ll also find it easier to use names in your own scripts.
If you do refer to forms and elements as arrays, you can use the length
property to determine the number of objects in the array: document.forms.length
is the number of forms in a document, and document.gbForm.elements.length
is the number of elements in the gbForm
form.
You can also access form elements using the W3C DOM. In this case, you use an id
attribute on the form element in the HTML document, and use the document.getElementById()
method to find the object for the form. For example, this statement finds the object for the text field called name
and stores it in the name
variable:
name = document.getElementById("name");
This enables you to quickly access a form element without first finding the form
object. You can assign an id
to the <form>
tag and find the corresponding object if you need to work with the form’s properties and methods.
As a simple example of using forms, Listing 26.2 shows a form with name, address, and phone number fields, as well as a JavaScript function that displays the data from the form in a pop-up window.
Listing 26.2 A Form That Displays Data in a Pop-up Window
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Form Display Example</title>
<script type="text/javascript">
function display() {
dispWin = window.open('','NewWin',
'toolbar=no,status=no,width=300,height=200')
message = "<ul><li><strong>NAME: </strong>" +
document.form1.name.value;
message += "<li><strong>ADDRESS: </strong>" +
document.form1.address.value;
message += "<li><strong>PHONE: </strong>" +
document.form1.phone.value + "</ul>";
dispWin.document.write(message);
}
</script>
</head>
<body>
<h1>Form Display Example</h1>
<p>Enter the following information. When you press the Display
button, the data you entered will be displayed in a pop-up.</p>
<form name="form1" method="get" action="">
<p>NAME: <input type="text" name="name" size="50" /></p>
<p>ADDRESS: <input type="text" name="address" size="50" /></p>
<p>PHONE: <input type="text" name="phone" size="50" /></p>
<p><input type="button" value="Display" onclick="display();" /></p>
</form>
</body>
</html>
Here is a breakdown of how this HTML document and script work:
• The <script>
section in the document’s header defines a function called display()
that opens a new window and displays the information from the form.
• The <form>
tag begins the form. Because this form is handled entirely by JavaScript, the form action
and method
have no value.
• The <input />
tags define the form’s three fields: yourname
, address
, and phone
. The last <input />
tag defines the Display button, which is set to run the display()
function.
Figure 26.2 shows this form in action. The Display button has been pressed, and the pop-up window shows the results.
Figure 26.2 Displaying data from a form in a pop-up window.
One easy way to use a form is to send the results by email. You can do this without using any JavaScript, although you could use JavaScript to validate the information entered (as you’ll learn later in this chapter).
To send a form’s results by email, you use the mailto:
action in the form’s action
attribute. Listing 26.3 is a modified version of the name and address form from Listing 26.2 that sends the results by email.
Listing 26.3 Sending a Form’s Results by Email
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Form Submit Example</title>
</head>
<body>
<h1>Form Submit Example</h1>
<p>Enter the following information. When you press the Send
button, the data you entered will be send via e-mail.</p>
<form name="form1" method="post" action="mailto:[email protected]"
enctype="text/plain">
<p>NAME: <input type="text" name="name" size="50" /></p>
<p>ADDRESS: <input type="text" name="address" size="50" /></p>
<p>PHONE: <input type="text" name="phone" size="50" /></p>
<p><input type="submit" value="Submit Form" /></p>
</form>
</body>
</html>
Caution
Because this technique does not consistently work on all browsers, I don’t recommend you use it. Some browsers will invoke your mail client; others will send the form data via your browser-based email account. This example is offered more as an example of a process you could use JavaScript to accomplish and might see in many scripts you find on the web. For a more reliable way of sending form results, you can use a server-side form-to-email script; your hosting provider will likely have one or more available for your use.
To use this form, change [email protected]
in the action
attribute of the <form>
tag to your email address. Notice the enctype="text/plain"
attribute in the <form>
tag. This ensures that the information in the email message will be in a readable plain-text format rather than encoded.
Although this provides a quick and dirty way of retrieving data from a form, the disadvantage of this technique is that it is highly browser dependent. Whether it will work for each user of your page depends on the configuration of her browser and email client.
This chapter demonstrated how to create HTML forms, which allow your visitors to provide information to you.
You learned about all the major form elements and how form-processing scripts interpret the names and value attributes of those elements. When you are ready to try a back-end form processing script, you’re now well-versed in the front-end details.
You also learned how form elements can be used with JavaScript. You learned about the form
object and the objects for the various form elements and used them in several sample scripts.
We stopped short of doing anything in-depth with that information because form handling requires an external script to process that form. You did learn one way to send simple form data by email and how to use JavaScript to validate a form before it is submitted.
Table 26.1 summarizes the HTML tags and attributes covered in this chapter.
Table 26.1 HTML Tags and Attributes Covered in Chapter 26
Q. If I use JavaScript to add validation and other features to my form, can users with non-JavaScript browsers still use the form?
A. Yes, if you’re careful. Be sure to use a Submit button rather than the submit
action. Also, the server-side script might receive nonvalidated data, so be sure to include the same validation in the CGI script. Non-JavaScript users will be able to use the form, but won’t receive instant feedback about their errors.
Q. Is there any way to create a large number of text fields without dealing with different names for all of them?
A. Yes. If you use the same name for several elements in the form, their objects will form an array. For example, if you defined 20 text fields with the name member
, you could refer to them as member[0]
through member[19]
. This also works with other types of form elements.
Q. Is there a way to place the cursor on a particular field when the form is loaded or after my validation routine displays an error message?
A. Yes. You can use the field’s focus()
method to send the cursor there. To do this when the page loads, you can use the onLoad
method in the <body>
tag. However, there is no way to place the cursor in a particular position within the field.
The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.
1. What HTML code would you use to create a guestbook form that asks someone for his name and gender? Assume that you have a form-processing script set up at /scripts/formscript
and that you need to include the following hidden input element to tell the script where to send the form results:
<input type="hidden" name="mailto" value="[email protected]" />
2. If you created an image named submit.gif
, how would you use it as the Submit button for the form you created in Question 1?
3. Which of these attributes of a <form>
tag determines where the data will be sent?
a. action
b. method
c. name
4. Where do you place the onsubmit
event handler to validate a form?
a. In the <body>
tag
b. In the <form>
tag
c. In the <input />
tag for the Submit button
1. You would use HTML code similar to the following (with the appropriate DOCTYPE and other structural markup, of course):
<form name="form1" method="post" action="/scripts/formscript">
<input type="hidden" name="mailto" value="[email protected]" />
<p>Your Name: <input type="text" name="name" size="50" /></p>
<p>Your Gender:
<input type="radio" name="gender" value="male" /> male
<input type="radio" name="gender" value="female" /> female
<input type="radio" name="gender" value="mind your business" />
mind your business </p>
<p><input type="submit" value="Submit Form" /></p>
</form>
2. Replace the following code:
<input type="submit" value="Submit Form" />
with this code:
<input type="image" src="submit.gif" />
3. a. The action
attribute determines where the data is sent.
4. b. You place the onsubmit
event handler in the <form>
tag.
• Create a form using all the different types of input elements and selection lists to make sure you understand how each of them works.
• Change the validate
function in Listing 26.4 so that after a message is displayed indicating that a field is wrong, the cursor is moved to that field. (Use the focus
method for the appropriate form element.)
• Add a text field to the form in Listing 26.4 for an email address. Add a feature to the validate
function that verifies that the email address is at least five characters and that it contains the @
symbol.
• Investigate the form-handling options at your web-hosting provider and use a script made available to you by the web-hosting provider to process the form you created in the previous exercise.
3.149.229.19