Laura Lemay's Teach Yourself Web Pub. W/HTML 3.2 twp18.htm

- — 18 —Basic Forms

- Anatomy of a Form

- Exercise 18.1: Tell me your name.

- Simple Form Layout

- The Submit Button

- Text Input Fields

- Radio Buttons
- Check Boxes
- Images
- Setting and Resetting Default Values

- Exercise 18.2: The Surrealist Census.

- More Forms Layout

- Selections
- Text Areas
- Hidden Fields

- Uploading Files Using Forms
- Summary
- Q&A

#
— 18 —
Basic Forms

Everything you've learned up to this point has involved your giving information to your readers. That information may just be text or images, it may be multimedia, or it may be a sophisticated, complex presentation using frames, image maps, and other bits of advanced Web publishing. But basically you're doing all the work, and your readers are simply sitting and reading and following links and digesting the information they've been presented.

Fill-in forms change all that. Forms make it possible for you to transform your Web pages from primarily text and graphics that your readers passively browse to interactive "toys," surveys, and presentations that can provide different options based on the readers' input.

Forms are the last of the major groups of HTML tags you'll learn about in this book (there are still a few minor tags left after this). And unlike many of the other tags you've learned about, forms are part of HTML 2.0 and are widely supported by just about every browser on the market. In this chapter you'll learn about the HTML part of forms; tomorrow you'll learn about the server-side programs you use to process information you get back from forms. In particular, today you learn about:

- Each part of the form on both the browser and server side, and how it all works
- The basic form input elements: text fields, radio buttons, and check boxes, as well as buttons for submitting and resetting the form
- Other form elements: text areas, menus of options, and hidden fields
- Some basic information about form-based file upload, a new feature that allows your readers to send whole files to you via a form

###
Anatomy of a Form

Creating a form usually involves two independent steps: creating the layout for the form itself and then writing a script program on the server side (called a CGI script or program) to process the information you get back from a form. Today you'll learn about the HTML side of the process, and tomorrow you'll learn all about CGI scripts.

To create a form, you use (guess!) the <FORM> tag. Inside the opening and closing FORM tags are each of the individual form elements plus any other HTML content to create a layout for that form (paragraphs, headings, tables, and so on). You can include as many different forms on a page as you want to, but you can't nest forms—that is, you can't include a <FORM> tag inside another FORM.

The opening tag of the FORM element usually includes two attributes: METHOD and ACTION. The METHOD attribute can be either GET or POST, which determines how your form data is sent to the script to process it. You'll learn more about GET and POST tomorrow.

The ACTION attribute is a pointer to the script that processes the form on the server side. The ACTION can be indicated by a relative path or by a full URL to a script on your server or somewhere else. For example, the following <FORM> tag would call a script called form-name in a cgi-bin directory on the server www.myserver.com:

    <FORM METHOD=POST ACTION="http://www.myserver.com/cgi-bin/form-name">

    ...

    </FORM>

Again, you'll learn more about both of these attributes tomorrow when we delve more into CGI scripts. For today, so we can test the output of our forms, we're going to be using a boilerplate form template that simply spits back what it gets. In each of the forms today, you'll be using POST as the METHOD, and the action will be the URL of a special script called post-query:

    <FORM METHOD=POST ACTION="http://www.mcp.com/cgi-bin/post-query">

    ...

    </FORM>

This particular example uses the post-query script on the server www.mcp.com (the server for the publisher of this book). The post-query script is part of the standard NCSA server distribution and may be available on your own server. Check with your Webmaster to see if it exists on your server; your forms will work that much faster if you work with a copy closer to you.

#####
Exercise 18.1: Tell me your name.

Let's try a simple example. In this example, you'll create the form shown in Figure 18.1. This form does absolutely nothing but prompt you for your name. In this form, you would enter your name and press the Submit button (or select the Submit link, in nongraphical browsers). Submit is what sends all the form data back to the server for processing. Then, on the server, a script would do something to that name (store it in a database, mail it to someone for further processing, plaster it across Times square, and so on).

Figure 18.1. The Tell Me Your Name form.

Most browsers provide a shortcut: If there is only one text field on the page (besides Submit), you can just press Return to activate the form.

In this chapter we're just going to do the layout. Let's create this form so you can get the basic idea of how it works. As with all HTML documents, start with a basic framework, with just a single level-two heading that says Who are you?:

    <HTML><HEAD>

    <TITLE>Tell Me Your Name</TITLE>

    </HEAD><BODY>

    <H2>Who are you?</H2>

    </BODY>

    </HTML>

Now, add the form. First, add that template for post-query I mentioned earlier:

    <HTML><HEAD>

    <TITLE>Tell Me Your Name</TITLE>

    </HEAD><BODY>

    <H2>Who are you?</H2>

    <FORM METHOD=POST ACTION="http://www.mcp.com/cgi-bin/post-query">

    </FORM>

    </BODY>

    </HTML>

With the form framework in place, we can add the elements of the form. Note that <FORM> doesn't specify the appearance and layout of the form; you'll have to use other HTML tags for that (and, in fact, if you looked at this page in a browser now, you wouldn't see anything on the page that looked like a form).

The first element inside the form is the text-entry area for the name. First, include the prompt, just as you would any other line of text in HTML:

    <P>Enter your Name:

Then add the HTML code that indicates a text-input field:

    <P>Enter your Name: <INPUT NAME="theName"></P>

The <INPUT> tag indicates a simple form element. (There are also several other form elements that use tags other than <INPUT>, but <INPUT> is the most common one.) <INPUT> usually takes at least two attributes: TYPE and NAME.

The TYPE attribute is the kind of form element this is. There are several choices, including "text" for text-entry fields, "radio" for radio buttons, and "check" for check boxes. If you leave the TYPE attribute out, as we've done here, the element will be a text-entry field.

The NAME attribute indicates the name of this element. When your form is submitted to the server, the CGI script that processes it gets the form data as a series of name and value pairs. The value is the actual value your reader enters; the name is the value of this attribute. By including a sensible name for each element, you can easily match up which answer goes with which question.

You can put anything you want as the name of the element, but as with all good programming conventions, it's most useful if you use a descriptive name. Here we've picked the name theName. (Descriptive, yes?)

Now add the final form element: the submit button (or link). Most forms require the use of a submit button; however, if you have only one text field in the form, you can leave it off. The form will be submitted when the reader presses Return.

    <P><INPUT TYPE="submit"></P>

You'll use the <INPUT> tag for this element as well. The TYPE attribute is set to the special type of "submit" which creates a submit button for the form. The submit button doesn't require a name if there's only one of them; you'll learn how to create forms with multiple submit buttons later on.

It's a good practice to always include a submit button on your form, even if there's only one text field. The submit button is so common that your readers may become confused if it's not there.

Note that each element includes tags for formatting, just as if this were text; form elements follow the same rules as text in terms of how your browser formats them. Without the <P> tags, you'd end up with all the elements in the form on the same line.

So, now you have a simple form with two elements. The final HTML code to create this form looks like this:

    <HTML><HEAD>

    <TITLE>Tell Me Your Name</TITLE>

    </HEAD><BODY>

    <H2>Who are you?</H2>

    <FORM METHOD="POST" ACTION="http://www.mcp.com/cgi-bin/post-query">

    <P>Enter your Name: <INPUT NAME="theName"></P>

    <P><INPUT TYPE="submit"></P>

    </FORM>

    </BODY></HTML>

So what happens if you do submit the form? The form data is sent back to the server, and the post-query CGI script is called. The post-query script does nothing except return the names and values that you had in the original form. Figure 18.2 shows the output from a form submitted with my name in it:

Figure 18.2. The output from post-query.

###
Simple Form Layout

So now that you've got the basics down, I'm sure you want to know exactly what kind of nifty interface elements you can put in a form.

In this section, you'll learn about the <INPUT> tag and the simple form elements you can create with it. There are a few other elements you can use for complex form input; you'll learn about those later in the chapter.

Each of the elements described in this section goes inside a <FORM>...</FORM> tag. In these examples, we'll continue to use the post-query script as the form's ACTION, which returns the name and value pairs it is given.

####
The Submit Button

Submit buttons (or submit links in nongraphical browsers; for the sake of simplicity, let's just call them buttons) tell the browser to send the form data to the server. You should include at least one submit button on every form even though forms with only one text field don't require them. To create a submit button, use "SUBMIT" as the TYPE attribute in an <INPUT> tag:

    <INPUT TYPE="SUBMIT">

You can change the label text of the button by using the VALUE attribute:

    <INPUT TYPE="SUBMIT" VALUE="Submit Query">

You can have multiple submit buttons in a form by including the NAME attribute inside the <INPUT> tag. Both the NAME and the VALUE of the submit button are then sent to the server for processing; you'll have to test for those name/value pairs when you write your CGI script to see which submit button was pressed. So, for example, you could use submit buttons inside a form for virtual directions, like this:

    <INPUT TYPE="SUBMIT" NAME="left" VALUE="Left">

    <INPUT TYPE="SUBMIT" NAME="right" VALUE="Right">

    <INPUT TYPE="SUBMIT" NAME="up" VALUE="Up">

    <INPUT TYPE="SUBMIT" NAME="down" VALUE="Down">

    <INPUT TYPE="SUBMIT" NAME="forward" VALUE="Forward">

    <INPUT TYPE="SUBMIT" NAME="back" VALUE="Back">

The following input and output example shows two simple forms with submit buttons: one with a default button and one with a custom label. Figure 18.3 shows the output in Netscape, and Figure 18.4 shows the output in Lynx.

Figure 18.3. The output in Netscape.

Figure 18.4. The output in Lynx.

These figures show how the buttons appear in Netscape for the Macintosh. The buttons look slightly different in Netscape for other platforms, and may look entirely different in other browsers.

    <FORM METHOD=POST ACTION="http://www.mcp.com/cgi-bin/post-query">

    <INPUT TYPE="SUBMIT">

    </FORM>

    <UL>

    <FORM METHOD=POST ACTION="http://www.mcp.com/cgi-bin/post-query">

    <INPUT TYPE="SUBMIT" VALUE="Press Here">

    </FORM>

###
Text Input Fields

Text fields enable your reader to type text into a single-line field. For multiple-line fields, use the <TEXTAREA> element, described later in this chapter.

To create a text-entry field, you can either use TYPE="text" in the <INPUT> tag or leave off the TYPE specification altogether. The default TYPE for the <INPUT> tag is "text". You must also include a NAME attribute. NAME indicates the name of this field as passed to the script processing the form.

    <INPUT TYPE="text" NAME="myText">

You can also include the attributes SIZE and MAXLENGTH in the <INPUT> tag. SIZE indicates the length of the text-entry field, in characters; the field is 20 characters by default. Your readers can enter as many characters as they want. The field will scroll horizontally as your reader types. Try to keep the SIZE under 50 characters so that it will fit on most screens.

    <INPUT TYPE="text" NAME="longText" SIZE="50">

MAXLENGTH enables you to limit the number of characters that your reader can type into a text field (refusing any further characters). If MAXLENGTH is less than SIZE, browsers will sometimes draw a text field as large as MAXLENGTH.

In addition to regular text fields, there are also password fields, indicated by TYPE=password. Password text fields are identical to ordinary text fields, except that all the characters typed are echoed back in the browser (masked) as asterisks or bullets (see Figure 18.5).

    <INPUT TYPE="PASSWORD" NAME="passwd">

Figure 18.5. Password fields.

Despite the masking of characters in the browser, password fields are not secure. The password is sent to the server in clear text; that is, anyone could intercept the password and be able to read it. The masking is simply a convenience.

This input and output example shows several text fields and their results in Netscape (Figure 18.6) and Lynx (Figure 18.7).

    <P>Enter your Name: <INPUT TYPE="TEXT" NAME="theName"><BR>

    Enter your Age:

    <INPUT TYPE="TEXT" NAME="theAge" SIZE="3" MAXLENGTH="3"><BR>

    Enter your Address:

    <INPUT TYPE="TEXT" NAME="theAddress" SIZE="80"></P>

Figure 18.6. The output in Netscape.

Figure 18.7. The output in Lynx.

####
Radio Buttons

Radio buttons indicate a list of items, of which only one can be chosen. If one radio button in a list is selected, all the other radio buttons in the same list are deselected.

Radio buttons use "radio" for their TYPE attribute. You indicate groups of radio buttons using the same NAME for each button in the group. In addition, each radio button in the group must have a unique VALUE attribute, indicating the selection's value.

    <OL>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="animal">Animal<BR>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="vegetable">Vegetable<BR>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="mineral">Mineral<BR>

    </OL>

You can use multiple, independent groups of radio buttons by using different names for each group:

    <OL>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="animal">Animal<BR>

    <OL>

    <LI><INPUT TYPE="radio" NAME="theAnimal" VALUE="cat">Cat

    <LI><INPUT TYPE="radio" NAME="theAnimal" VALUE="dog">Dog

    <LI><INPUT TYPE="radio" NAME="theAnimal" VALUE="fish">fish

    </OL>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="vegetable">Vegetable<BR>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="mineral">Mineral<BR>

    </OL>

By default, all radio buttons are off (unselected). With radio buttons, because you generally have at least one choice, it's a good idea to make one button selected by default. You can determine the default radio button in a group using the CHECKED attribute:

    <OL>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="animal" CHECKED>Animal<BR>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="vegetable">Vegetable<BR>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="mineral">Mineral<BR>

    </OL>

When the form is submitted, a single name/value pair for the group of buttons is passed to the script. That pair includes the NAME attribute for each group of radio buttons and the VALUE attribute of the button that is currently selected.

Here's an input and output example that shows two groups of radio buttons and how they look in Netscape (Figure 18.8) and Lynx (Figure 18.9).

    <OL>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="animal" CHECKED>Animal<BR>

    <OL>

    <LI><INPUT TYPE="radio" NAME="theAnimal" VALUE="cat" CHECKED>Cat

    <LI><INPUT TYPE="radio" NAME="theAnimal" VALUE="dog">Dog

    <LI><INPUT TYPE="radio" NAME="theAnimal" VALUE="fish">fish

    </OL>

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="vegetable">Vegetable

    <LI><INPUT TYPE="radio" NAME="theType" VALUE="mineral">Mineral

    </OL>

Figure 18.8. The output in Netscape.

Figure 18.9. The output in Lynx.

####
Check Boxes

Check boxes make it possible to choose multiple items in a list. Each check box can be either checked or unchecked (the default is unchecked). Check boxes use "checkbox" as their TYPE attribute:

    <UL>

    <LI><INPUT TYPE="checkbox" NAME="red">Red

    <LI><INPUT TYPE="checkbox" NAME="green">Green

    <LI><INPUT TYPE="checkbox" NAME="blue">Blue

    </UL>

When the form is submitted, only the name/value pairs for each selected check box are submitted (unchecked check boxes are ignored). By default, each name/value pair for a checked check box has a value of ON in the script that processes the form. You can also use the VALUE attribute to indicate a value you would prefer to see in your script. In this example, each check box that is selected will have the name given by the NAME attribute and the value chosen:

    <UL>

    <LI><INPUT TYPE="checkbox" NAME="red" VALUE="chosen">Red

    <LI><INPUT TYPE="checkbox" NAME="green" VALUE="chosen">Green

    <LI><INPUT TYPE="checkbox" NAME="blue" VALUE="chosen">Blue

    </UL>

You can also implement check box lists such that elements have the same NAME attribute, similar to radio buttons. Notice, however, that this means your script will end up with several name/value pairs having the same name (each check box that is selected will be submitted to the script), and you'll have to take that into account when you process the input in your script.

As with radio buttons, you can use the CHECKED attribute to indicate that a check box is checked by default.

Here's another one of those input and output examples, with a series of check boxes and how they look in Netscape (Figure 18.10) and Lynx (Figure 18.11).

    <P>Profession (choose all that apply): </P>

    <UL>

    <LI><INPUT TYPE="checkbox" NAME="doctor" CHECKED>Doctor

    <LI><INPUT TYPE="checkbox" NAME="lawyer">Lawyer

    <LI><INPUT TYPE="checkbox" NAME="teacher" CHECKED>Teacher

    <LI><INPUT TYPE="checkbox" NAME="nerd">Programmer

    </UL>

Figure 18.10. The output in Netscape.

Figure 18.11. The output in Lynx.

####
Images

Forms also give you an alternate way of implementing image maps using the TYPE=IMAGE attribute to the <INPUT> tag. Use TYPE=IMAGE with the SRC attribute which, just like SRC in <IMG>, indicates the pathname or URL to an IMAGE:

    <INPUT TYPE="image" SRC="usamap.gif" NAME="map">

Images in forms behave just like image maps; when you click somewhere on the image, the form is submitted back to the server. The coordinates of the point where you clicked are submitted as part of that FORM data, with the value of the NAME attribute included twice with .x and .y appended for each coordinate. So, for example, if this image had the name map, the x-coordinate would be contained in the map.x value, and the y-coordinate would be contained in the map.y value.

In the CGI script to process the form, you'll have to handle those coordinates yourself. Since standard image maps do a much better job of this, TYPE=IMAGE is rarely used any more to create an image map. What it is used much more commonly is as a replacement submit button. Because the image submits the form when it's selected, you can create an image for the submit button to replace the bland default button for submit.

####
Setting and Resetting Default Values

Each form element can have a default value that is entered or selected when the form is viewed:

- For text fields, use the VALUE attribute with a string for the default value. The VALUE is entered in the box automatically when the form is displayed.
- For check boxes and radio buttons, the attribute CHECKED selects that element by default.

In addition to the default values for each element, you can include a reset button, similar to the submit button, on your form. The reset button clears all selections or entries your reader has made and resets them to their default values. Also like submit, a VALUE attribute indicates the label for the button:

    <INPUT TYPE="RESET" VALUE="Reset Defaults">

#####
Exercise 18.2: The Surrealist Census.

Now, let's create a more complicated form example. In this example, The Surrealist Society of America has created a small census via an interactive form on the World Wide Web. Figure 18.12 shows that census.

Figure 18.12. The Surrealist Society's census form.

The form to create the census falls roughly into three parts: the name field, the radio buttons for choosing the sex, and a set of check boxes for various other options.

Start with the basic structure, as with all HTML documents. We'll use that post-query script as we did in all the previous examples:

    <HTML><HEAD>

    <TITLE>The Surrealist Census</TITLE>

    </HEAD><BODY>

    <H1>The Surrealist Census</H1>

    <P>Welcome to the Surrealist Census. Please fill out the following

    form to the best of your abilities.</P>

    <P>Use <STRONG>Submit</STRONG> to submit your results.</P>

    <HR>

    <FORM METHOD=POST ACTION="http://www.mcp.com/cgi-bin/post-query">

    </FORM>

    <HR>

    </BODY></HTML>

Note that in this example I've included rule lines before and after the form. Because the form is a discrete element on the page, it makes sense to visually separate it from the other parts of the page. This is especially important if you have multiple forms on the same page; separating them with rule lines or in some other way visually divides them from the other content on the page.

Now, let's add the first element for the reader's name. This is essentially the same element that we used in the previous example, with the name of the element theName:

    <P><STRONG>Name: </STRONG><INPUT TYPE="TEXT" NAME="theName"></P>

The second part of the form is a series of radio buttons for Sex. There are three: Male, Female, and Null (remember, this is The Surrealist Census). Since radio buttons are mutually exclusive (only one can be selected at a time), we'll give all three buttons the same value for NAME (theSex):

    <P><STRONG>Sex: </STRONG>

    <INPUT TYPE="radio" NAME="theSex" VALUE="male">Male

    <INPUT TYPE="radio" NAME="theSex" VALUE="female">Female

    <INPUT TYPE="radio" NAME="theSex" VALUE="null">Null

    </P>

Even though each <INPUT> tag is arranged on a separate line, the radio button elements are formatted on a single line. Always remember that form elements do not include formatting; you have to include other HTML tags to arrange them in the right spots.

Now, let's add the last part of the form: the list of Contains check boxes:

    <P><STRONG>Contains (Select all that Apply): </STRONG><BR>

    <INPUT TYPE="checkbox" NAME="humor">Vitreous Humor<BR>

    <INPUT TYPE="checkbox" NAME="fish">Fish<BR>

    <INPUT TYPE="checkbox" NAME="glycol">Propylene Glycol<BR>

    <INPUT TYPE="checkbox" NAME="svga">SVGA Support<BR>

    <INPUT TYPE="checkbox" NAME="angst">Angst<BR>

    <INPUT TYPE="checkbox" NAME="catcon">Catalytic Converter<BR>

    <INPUT TYPE="checkbox" NAME="vitamin">Ten Essential Vitamins and Nutrients<BR>

    </P>

Unlike radio buttons, any number of check boxes can be selected, so each value of NAME is unique.

Finally, add the submit button so that the form can be submitted to the server. A nice touch is to also include a "Clear Form" button. Both buttons have special labels specific to this form:

    <P><INPUT TYPE="SUBMIT" VALUE="Submit Your Votes">

    <INPUT TYPE="RESET" VALUE="Clear Form"></P>

Whew! With all the elements in place, here's what the entire HTML file for the form looks like:

    <HTML><HEAD>

    <TITLE>The Surrealist Census</TITLE>

    </HEAD><BODY>

    <H1>The Surrealist Census</H1>

    <P>Welcome to the Surrealist Census. Please fill out the following

    form to the best of your abilities.</P>

    <P>Use <STRONG>Submit</STRONG> to submit your results.</P>

    <HR>

    <FORM METHOD="POST" ACTION="http://www.mcp.com/cgi-bin/post-query">

    <P><STRONG>Name: </STRONG><INPUT TYPE="TEXT" NAME="theName"></P>

    <P><STRONG>Sex: </STRONG>

    <INPUT TYPE="radio" NAME="theSex" VALUE="male">Male

    <INPUT TYPE="radio" NAME="theSex" VALUE="female">Female

    <INPUT TYPE="radio" NAME="theSex" VALUE="null">Null

    </P>

    <P><STRONG>Contains (Select all that Apply): </STRONG><BR>

    <INPUT TYPE="checkbox" NAME="humor">Vitreous Humor<BR>

    <INPUT TYPE="checkbox" NAME="fish">Fish<BR>

    <INPUT TYPE="checkbox" NAME="glycol">Propylene Glycol<BR>

    <INPUT TYPE="checkbox" NAME="svga">SVGA Support<BR>

    <INPUT TYPE="checkbox" NAME="angst">Angst<BR>

    <INPUT TYPE="checkbox" NAME="catcon">Catalytic Converter<BR>

    <INPUT TYPE="checkbox" NAME="vitamin">Ten Essential Vitamins and Nutrients<BR>

    </P>

    <P><INPUT TYPE="SUBMIT" VALUE="Submit Your Votes">

    <INPUT TYPE="RESET" VALUE="Clear Form"></P>

    </FORM>

    <HR>

    </BODY></HTML>

Try selecting different parts of the form and seeing what you get back using post-query. Figure 18.13 shows one sample I used; Figure 18.14 shows the results I got back.

Figure 18.13. A sample surrealist.

Figure 18.14. The results back from the sample surrealist.

###
More Forms Layout

In addition to the <INPUT> tag with its many options, there are also two other tags that create form elements: SELECT, which has the ability to create pull-down menus and scrolling lists, and TEXTAREA, for allowing the reader to enter long blocks of text.

This section describes these other two tags. It also explains how to create "hidden" elements—form elements that don't actually show up on the page but exist in the form nonetheless.

####
Selections

Selections enable the reader to select one or more items from a menu or a scrolling list. They're similar in functionality to radio buttons or check boxes, but they're displayed in a different way on-screen.

Selections are indicated by the <SELECT> tag, and individual options within the selection are indicated by the <OPTION> tag. The <SELECT> tag also contains a NAME attribute to hold its value when the form is submitted.

<SELECT> and <OPTION> work much like lists do, with the entire selection surrounded by the opening and closing <SELECT> tags. Each option begins with a single-sided <OPTION, like this:

    <P>Select a hair color:

    <SELECT NAME="hcolor">

    <OPTION>Black

    <OPTION>Blonde

    <OPTION>Brown

    <OPTION>Red

    <OPTION>Blue

    </SELECT></P>

When the form is submitted, the value of the entire selection is the text that follows the selected <OPTION> tag—in this case, Brown, Red, Blue, and so on. You can also use the VALUE attribute with each <OPTION> tag to indicate a different value than the one that appears on the screen:

    <OPTION VALUE="auburn">Red

Selections of this sort are generally formatted in graphical browsers as popup menus, as shown in Figure 18.15.

Figure 18.15. Selections.

Usually, the first option in the list is the one that is selected and displayed as the initial value. You can set the default item to be initially selected by using the SELECTED attribute, part of the <OPTION> tag:

    <P>Select a hair color:

    <SELECT NAME="hcolor">

    <OPTION>Black

    <OPTION>Blonde

    <OPTION SELECTED>Brown

    <OPTION>Red

    <OPTION>Blue

    </SELECT></P>

By default, selections act like radio buttons; that is, only one item can be selected at a time. You can change the behavior of selections to allow multiple options to be selected by using the MULTIPLE attribute, part of the <SELECT> tag:

    <P>Shopping List:

    <SELECT NAME="shopping" MULTIPLE>

    <OPTION>Butter

    <OPTION>Milk

    <OPTION>Flour

    <OPTION>Eggs

    <OPTION>Cheese

    <OPTION>Beer

    <OPTION>Pasta

    <OPTION>Mushrooms

    </SELECT></P>

Be careful when you use MULTIPLE in the script that will process this form. Remember that each selection list only has one possible NAME. This means that if you have multiple values in a selection list, all of those values will be submitted to your script, and the program you use to decode the input might store those in some special way.

Each browser determines how the reader makes multiple choices. Usually, the reader must hold down a key while making multiple selections, but that particular key may vary from browser to browser.

The optional <SIZE> attribute usually displays the selection as a scrolling list in graphical browsers, with the number of elements in the SIZE attribute visible on the form itself, as shown in the following code. (Figure 18.16 shows an example.)

    <P>Shopping List:

    <SELECT NAME="shopping" MULTIPLE SIZE="5">

    <OPTION>Butter

    <OPTION>Milk

    <OPTION>Flour

    <OPTION>Eggs

    <OPTION>Cheese

    <OPTION>Beer

    <OPTION>Pasta

    <OPTION>Mushrooms

    </SELECT></P>

Figure 18.16. Selections with SIZE.

Here's an input and output example that shows a simple selection list and how it appears in Netscape for the Mac (Figure 18.17). Note that selection lists may have a different appearance if you're viewing them on different computer systems or in different browsers.

    <FORM METHOD="POST" ACTION="http://www.mcp.com/cgi-bin/post-query">

    <P>Select a hair color:

    <SELECT NAME="hcolor">

    <OPTION>Black

    <OPTION>Blonde

    <OPTION SELECTED>Brown

    <OPTION>Red

    <OPTION>Blue

    </SELECT></P>

    </FORM>

Figure 18.17. The output in Netscape.

####
Text Areas

Text areas are input fields in which the reader can type. Unlike regular text-input fields (<INPUT TYPE="text">), text areas can contain many lines of text, making them extremely useful for forms that require extensive input. For example, if you wanted to create a form that enabled readers to compose electronic mail, you might use a text area for the body of the message.

To include a text area element in a form, use the <TEXTAREA> tag. <TEXTAREA> includes three attributes:

NAME | The name to be sent to the CGI script when the form is submitted
ROWS | The height of the text area element, in rows of text
COLS | The width of the text area element in columns (characters)

The <TEXTAREA> tag is a two-sided tag, and both sides must be used. If you have any default text you want to include in the text area, include it between the opening and closing tags. For example:

    <TEXTAREA NAME="theBody" ROWS="14" COLS="50">Enter your message here.</TEXTAREA>

The text in a text area is generally formatted in a fixed-width font such as Courier, but it's up to the browser to decide how to format it beyond that. Some browsers will allow text wrapping in text areas, others will scroll to the right. Some will allow scrolling if the text area fills up, whereas some others will just stop accepting input.

Netscape provides an extension to HTML that allows you to control text wrapping in the browser. By default in Netscape, text in a text area does not wrap; it simply scrolls to the right. You have to press Enter to get to the next line. Using the WRAP attribute to TEXTAREA, you can change the wrapping behavior:

WRAP=OFF | The default; text will be all on one line, scrolling to the right, until the reader presses Enter.
WRAP=SOFT | Causes the text to wrap automatically in the browser window, but is sent to the server as all one line.
WRAP=HARD | Causes the text to wrap automatically in the browser window. That text is also sent to the server with new-line characters at each point where the text wrapped.

This input and output example shows a simple text area in Netscape (Figure 18.18) and Lynx (Figure 18.19).

    <FORM METHOD="POST" ACTION="http://www.mcp.com/cgi-bin/post-query">

    <P>Enter any Comments you have about this Web page here:

    <TEXTAREA NAME="comment" ROWS="30" COLS="60">

    </TEXTAREA>

    </P>

    </FORM>

Figure 18.18. The output in Netscape.

Figure 18.19. The output in Lynx.

####
Hidden Fields

One value for the TYPE attribute to the <INPUT> tag I haven't mentioned is "HIDDEN". Hidden fields do not appear on the actual form; they are invisible in the browser display. They will still appear in your HTML code if someone decides to look at the HTML source for your page.

Hidden input elements look like this:

    <INPUT TYPE="HIDDEN" NAME="theName" VALUE="TheValue">

Why would you want to create a hidden form element? If it doesn't appear on the screen and the reader can't do anything with it, what's the point?

Let's take a hypothetical example. You create a simple form. In the script that processes the first form, you create a second form based on the input from the first form. The script to process the second form takes the information from both the first and second forms and creates a reply based on that information. Figure 18.20 shows how all this flows.

Figure 18.20. Form to form to reply.

How would you pass the information from the first form to the script that processes the second form? You can do one of two things:

- Write the information from the first form to a temporary file, and then read that file back in again when the second form starts up.
- In the first script that constructs the second form, create hidden fields in the form with the appropriate information in NAME and VALUE fields. Then those names and values will be passed automatically to the second script when the reader submits the second form.

See? Hidden elements do make sense, particularly when you get involved in generating forms from forms.

###
Uploading Files Using Forms

A recent proposal for modifying the standard definition of forms includes allowing forms to be used for uploading whole files full of data to a server. With forms the way they are now, you can upload a text file by copying it into a text area, but there's no easy way to upload an image or other binary file.

File upload is a proposed enhancement to HTML, and has been extensively discussed by the various HTML standards organizations. At the moment, however, Netscape 2.0 is the only browser that supports form-based file upload, and even then, dealing with the input on the server side is significantly more difficult than dealing with simple form input. Keep all this in mind as you read this section; file upload is very new indeed.

If you do decide to play with form-based file upload, you'll need to make two simple changes to the HTML code for your form. The first is to include the ENCTYPE="multipart/form-data" attribute inside your <FORM> tag, like this:

    <FORM METHOD=POST ENCTYPE="multipart/form-data"

    ACTION="http://www.myserver.com/cgi-bin/uploadit">

    ...

    </FORM>

ENCTYPE (short for enclosure type) isn't new; it's actually part of standard HTML 2.0, and its default value is application/x-www-form-urlencoded. Because the vast majority of forms use that default enclosure type and few browsers or servers know how to deal with any other enclosure type, you don't really need to know anything about ENCTYPE unless you're working with file upload.

The second thing you'll need to add to your form is a new kind of <INPUT> tag. A new value for the TYPE attribute, TYPE="file", inserts a file-upload element (a text field and a button labeled "Browse" that lets you browse the local file system). Here's an example of a form with nothing but a file-upload element in it. Figure 18.21 shows how this appears in Netscape.

    <FORM ENCTYPE="multipart/form-data"

    ACTION="http://www.myserver.com/cgi-bin/upload" METHOD=POST>

    Send this file: <INPUT NAME="userfile" TYPE="file">

    <INPUT TYPE="submit" VALUE="Send File">

    </FORM>

Figure 18.21. Forms for file upload.

Note that because this is an entirely new kind of form, you won't be able to test this with the post-query program we've been using up to this point. You'll need a special script on the server side to deal with form-based file upload; I'll talk more about this in the next chapter on CGI scripts.

###
Summary

Text fields, radio buttons, check boxes, submit and reset buttons, selection lists, and text areas—all of these are form elements you can include on your Web pages to get information back from your reader. And in this chapter, you learned all about how to include each of these in your Web page, as well as how to construct the form itself so that when it's submitted it'll call the right programs on the server side to process the information.

Forms are an HTML 2.0 feature, and the tags for creating forms are widely supported in just about every available browser. Table 18.1 presents a summary of all the tags and attributes you learned about in this chapter.

Table 18.1. HTML tags from this chapter.

    Tag

    Use

<FORM>...</FORM> | A form. You can have multiple forms within a document, but forms cannot be nested.
ACTION | An attribute of the <FORM> tag indicating the CGI script to process the form input. Contains a relative path or URL to the script.
METHOD | An attribute of the <FORM> tag, indicating the method with which the form input is given to the script that processes the form. Possible values are GET and POST.
<INPUT> | A form element.
TYPE | An attribute of the <INPUT> tag indicating the type of form element. Possible values are CHECKBOX, HIDDEN, IMAGE, RADIO, RESET, SUBMIT, and TEXT.
CHECKBOX | Creates a check box.
HIDDEN | Creates a form element that is not presented but has a name and a value that can then be passed on to the script that processes the form input.
IMAGE | Creates a clickable image, similar to an image map, that behaves like a submit button.
RADIO | Creates a radio button.
RESET | Creates a button which resets the default values of the form, if any.
SUBMIT | Creates a button to submit the form to the script which processes the input.
TEXT | Creates a single-line text field.
VALUE | An attribute of the <INPUT> tag, indicating the default value for the form element, if any, or the value submitted with the NAME to the script. For SUBMIT and RESET buttons, VALUE indicates the label of the button.
SIZE | An attribute of the <INPUT> tag used only when TYPE is TEXT. Indicates the size of the text field, in characters.
MAXLENGTH | An attribute of the <INPUT> tag used only when TYPE is TEXT. Indicates the maximum number of characters this text field will accept.
CHECKED | An attribute of the <INPUT> tag used only when TYPE is CHECKBOX or RADIO. Indicates that this element is selected by default.
SRC | An attribute of the <INPUT> tag used only when TYPE is IMAGE. Indicates the path or URL to the image file.
FILE | An attribute of the <INPUT> tag which inserts a file-uploading form element: A text field and a Browse button that allow you to browse the local file system.
<SELECT> | A menu or scrolling list of items. Individual items are indicated by the <OPTION> tag.
MULTIPLE | An attribute of the <SELECT> tag indicating that multiple items in the list can be selected.
SIZE | An attribute of the <SELECT> tag which causes the list of items to be displayed as a scrolling list with the number of items indicated by SIZE visible.
<OPTION> | Individual items within a <SELECT> element.
SELECTED | An attribute of the <OPTION> tag indicating that this item is selected by default.
VALUE | An attribute of the <OPTION> tag indicating the value this option should have when the form is submitted.
<TEXTAREA> | A text-entry field with multiple lines.
ROWS | An attribute of the <TEXTAREA> tag indicating the height of the text field, in rows.
COLS | An attribute of the <TEXTAREA> tag indicating the width of the text field, in characters.
WRAP | A (Netscape) attribute of the <TEXTAREA> tag indicating how the text inside that text area will behave. Possible values are OFF (the default), in which no wrapping occurs; SOFT, in which wrapping occurs on-screen but the text is sent to the server as a single line; or HARD in which wrapping occurs on-screen and new lines are included in the text as submitted to the server.

###
Q&A

Q: I've got a form with a group of radio buttons, of which one has to be selected. When my form first comes up in a browser, none of them are selected, so if my reader doesn't choose one, I don't get any of the values. How can I make it so that one of them is selected?

A: Use the CHECKED attribute to set a default radio button out of the group. If your reader doesn't change it, the value of that radio button will be the one that's submitted.

Q: I'm having a hard time getting my form elements to lay out the way I want them. Nothing lines up right.

A: Form elements, like all HTML elements, lay out based on the size of the screen and the browser's rules for where things go on the screen.

I've seen two ways of affecting how forms are laid out. The first is to use <PRE>; the monospaced text affects the labels for the forms, but not the form elements themselves.

The second solution is to use tables without borders. You can get all your form elements to line up nicely by aligning them inside table cells.

Q: I have text areas in my forms. In Netscape, when I type into the text area, the line keeps going and going to the right; it never wraps onto the next line. Do I have to press Enter at the end of every line?

A: When you set up your form, include the WRAP attribute to indicate in Netscape how text inside the form will behave. WRAP=SOFT would be a good choice.