Index:
A form is a template for a form data set and an associated method and action URI. A form data set is a sequence of name/value pair fields. The names are specified on the NAME attributes of form input elements, and the values are given initial values by various forms of markup and edited by the user. The resulting form data set is used to access an information service as a function of the action and method.
Forms elements can be mixed in with document structuring elements. For example, a PRE element may contain a FORM element, or a FORM element may contain lists which contain INPUT elements. This gives considerable flexibility in designing the layout of forms.
<form method="post" enctype="text/plain" action="mailto:recipient@server.com?subject=SPAUG survey" name="formname">
(form elements and other HTML)
</form>
ACTION specifies the action URI for the form. This URI will point to a CGI script to decode the form results, to an online form handler (such as Response-O-Matic www.response-o-matic.com or FormMailer www.formmailer.net, or a mailto:[address]. To add additional email addresses after the first, separate with a comma (, ); the space is optional.
METHOD selects an HTTP method of accessing the action URI. There are two methods, GET (the default) and POST. Generally speaking, you use GET for only the simplest forms, or when you want the user to be able to bookmark the query or use it as a link - it will work just as if the user had filled in the form as before and submitted it. Use POST for forms with a lot of fields (GET might not be able to pass all the data) and for scripts that are supposed to change something on the server - you normally don't want anyone to do that from a bookmark or link.
METHOD="GET" Information from a form using the GET method is appended onto the end of the action URI being requested. Your CGI program will receive the encoded form input in the environment variable QUERY_STRING.
METHOD="POST" This method transmits all form input information immediately after the requested URI. Your CGI program will receive the encoded form input on stdin. The server will NOT send you an EOF on the end of the data, instead you should use the environment variable CONTENT_LENGTH to determine how much data you should read from stdin. Set a Subject for the email returned by appending ?subject=[subject] to the mailto: address as in the example above.
ENCTYPE specifies the media type used to encode the name/value pairs for transport, in case the protocol does not itself impose a format. With the POST method, the ENCTYPE attribute is a media type specifying the format of the posted data (by default application/x-www-form-urlencoded). If you use action="mailto:" the "text/plain" will give a readable message; if you use the default, you'll need to decode the result. Harry Sklar has a Word macro to do this at sklarnet.com/harzhelp.htm#macro.
NAME is optional but recommended for the first FORM on a page, and mandatory for more than one FORM per page.
The INPUT element represents a field for user input. The TYPE attribute discriminates among several variations of fields. The INPUT element has a number of attributes. The set of applicable attributes depends on the value of the TYPE attribute.
To ensure content accessibility in Web pages, intrinsic controls, such as an input of type radio or check box, you can use the label for element to associate text with another element:
<input type="radio" value="1" id="opt1"><label for="opt1">This is the first option.</label>
Further, there should be a method to differentiate among multiple choices. Instead of the inaccessible
<input type="radio" name="optAnimal">Bear
here's the example in an accessible form, using the id and label for elements:
<b>please choose your animal:</b><br>
<input type="radio" name="optAnimal" id="opt1"><label for="opt1">Bear</label>
<input type="radio" name="optAnimal" id="opt2"><label for="opt2">Goat</label>
The default value of the TYPE attribute is TEXT, indicating a single line text entry field. (Use the TEXTAREA element below for multi-line text fields.)
Required attributes are:
name for the form field corresponding to this element.
Optional attributes are:
maxlength="##" constrains the number of characters that can be entered into a text input field. If the value of MAXLENGTH is greater the the value of the SIZE attribute, the field will scroll. The default number of characters is unlimited.
size specifies the amount of display space allocated to this input field according to its type. The default depends on the browser.
value gives the initial value of the field. Give it a good name to prompt for correct user input, and so you receive the input in a useful format. See how the Zip Code is prompting for a 5+4 number.
For example, coding:
<p>Street Address: <input name="street" type="text">
<br>Postal City code: <input name="city" type="text" size="16" maxlength="16">
<br>Zip Code: <input name="zip" type="text" size="10" maxlength="10" value="99999-9999"></p>
gives this result:
Street Address:
Postal City code:
Zip Code:
An INPUT element with type="password" is a text field as above, except that the value is obscured (usually the text is replaced with asterisks) as it is entered. In practice, you would probably not use a correct default password, and would leave value="" null.
For example:
Name: <input name="login" type="text"> Password: <input type="password" name="passwd" value="password">
gives this result:
Name: Password:
An input element with type="checkbox" represents a boolean choice. A set of such elements with the same name represents an n-of-many choice field, allowing the user to choose one or more or all of the options. Give each one the same name but a different value corresponding to the meaning of the box, and label each box before or after the input tag with a meaningful description, so users can know what they are checking. Note the type, name and value are not visible to the user, but will be returned after form submission to the form creator.
Required attributes are:
name for the form field corresponding to this element or group of elements.
value of the field contributed by this element, such as yes or appropriate and meaningful description.
Optional attributes are:
checked="checked" indicates that the initial state is on or checked.
For example:
<p>What flavors do you like?
<br><input type="checkbox" name="flavor" value="vanilla">Vanilla
<br><input type="checkbox" name="flavor" value="strawberry">Strawberry
<br><input type="checkbox" name="flavor" value"=chocolate" checked="checked">Chocolate</p>
gives this result:
What flavors do you like?
Vanilla
Strawberry
Chocolate
An element with input type="radio" represents a boolean choice. A set of two or more such elements with the same name represents a 1-of-many choice field. Radio buttons allow the user to choose one, but only one, of several options.. If none of the INPUT elements of a set of radio buttons specifies checked, the first radio button is set by default.
Required attributes are:
name for the form field corresponding to this element or group of elements.
value of the field contributed by this element, such as yes or appropriate description.
Optional attributes are:
checked="checked" indicates that the initial state is on or checked.
For example:
<p>Which is your favorite?
<br><input type="radio" name="flavor" value="vanilla">Vanilla
<br><input type="radio" name="flavor" value="strawberry">Strawberry
<br><input type="radio" name="flavor" value="chocolate" checked="checked">Chocolate
gives this result:
Which is your favorite?
Vanilla
Strawberry
Chocolate
Labeling a form control means more than just making sure the text that appears on the Web page is clear. It also means that you've used the LABEL element to clearly mark and describe what type of information you want the visitor to enter into each form control.
A little background information: A "form control" is a fancy term for a text box, checkbox, radio button, or any element in a form that allows the user to enter information or submit the form.
The LABEL element is an "explicit label" for the form control. By explicit, we mean that you're specifically providing information about each form element. Each form control should have its own LABEL. Add the FOR attribute to tie the LABEL to the form control's ID attribute.
For example, here's the code for a simple form using the LABEL element:
<form method="post" action="../cgi-bin/FormMail.pl" name="emailForm">
<label for="em_add">Email Address</label>
<input type="text" name="email" id="em_add">
<br>
<label for="comment_here">Send us your Comments!</label> <br>
<textarea name="comments" id="comment_here" cols="20" rows="5">
</textarea>
<br>
<input type="submit" value="Submit">
</form>
Note that we didn't add a LABEL attribute for the SUBMIT button. That's because screen readers read the text that's on the button. That's a handy feature, but does mean that you need to clearly define the button's use. A button with text like "Submit" or "Send" is fine. Try to avoid more oblique values like "Tell Us!" or "Done!"
You can also add the ACCESSKEY attribute to your LABEL element and make keyboard navigation easier for visitors.
An element with input type="image" specifies an image resource to display, and allows input of two form fields: the x and y coordinate of a pixel chosen from the image. The names of the fields are the name of the field with .x and .y appended. input type="image" implies input type="submit" processing; that is, when a pixel is chosen, the form as a whole is submitted.
Required attributes are:
name for the form field corresponding to this element or group of elements.
src is the URL of the image source.
Optional attributes are:
align to center, or align left or right.
For example:
<p>Choose a point on the map:<input type="image" name="point" src="../images/disk.gif" align="center">
gives this result:
Choose a point on the diskette:
An element input type="hidden" is a hidden field. The user cannot interact with this field because it is invisible; the value attribute specifies the value of the field.
Required attributes are:
name for the form field corresponding to this element or group of elements.
value is returned when the form is submitted.
there are no Optional attributes.
For example:
A hidden field between here<input type="hidden" name="context" value="some hidden text"> and here.
would give this (invisible) result:
A hidden field between here and here.
An element with input type="submit" creates a button that instructs the user to submit the form.
There are no Required attributes
Optional attributes are:
name sends the text given by the value attribute; if missing, nothing is sent.
value gives a label to the input button that the user can see.
For example,
You may submit this request internally: <input type="submit" name="recipient" value="internal"><br>
or to the external world: <input type="submit" name="recipient" value="world">
gives the result:
You may submit this request internally:
or to the external world:
An element with input type="reset" makes a button that resets the form to its initial state. The value attribute, if present, indicates a label for the input (button).
For example:
When you are finished, you may submit this request: <input type="submit" value="Do it!"><br>
You may clear the form and start over at any time: <input type="reset" value="start over">
gives this result:
When you are finished, you may submit this request:
You may clear the form and start over at any time:
select causes the form field to create a list of values (Pull Down List). The values are defined in option elements. The only thing you can put between <select> and </select> are <option> tags; no other HTML code is allowed.
Required attributes are:
name specifies the name of the form field.
</select> closing tag
Optional attributes are:
multiple indicates that more than one option may be included in the value.
size specifies the number of visible items. Select size="1" are typically pop-down menus, whereas select greater than one are typically Scrolling Lists.
By default, the first option is selected, unless a selected attribute is present on one of the option elements.
option can only occur within a select element. It represents one choice, is optionally closed </option> and has the following attributes:
selected indicates that this option is initially selected.
value indicates the value to be returned if this option is chosen. The field value defaults to the content of the option element.
The content of the option element is presented to the user to represent the option. It is returned if the value attribute is not present. It is safer to explicitly define appropriate, meaningful values, unless all are very simple text. Note vanilla has no value defined.
For example:
<select name="flavor" size="1">
<option value="vanilla">vanilla</option>
<option value="strawberry">strawberry</option>
<option value="rumrasin">rum and raisin</option>
<option value="peachorange" selected="selected">peach and orange</option>
</select>
gives the drop-down menu:
Note the name and value attributes for pull-down menus are shared between the <select> and <option> tags. You must assign a name to the <select> tag, but you assign the values to the <option> tags.
The purpose of the OPTGROUP element is to group different OPTION tags under a common name or label. This is an extracte from an article at NetMechanic Until recently, the OPTGROUP element belonged to that lonely category of valid HTML tags that most major browsers didn't recognize. Fortunately, Netscape 6.x and Explorer 6.0 for Windows have joined Explorer 5.0/Mac in supporting this handy way to categorize SELECT lists. Use it to make your lists easier to read and understand.
Add it to a regular SELECT list like this:
<SELECT NAME="Vacation Spots">
<OPTGROUP LABEL="USA Beaches">
<OPTION LABEL="Florida">Florida</OPTION>
<OPTION LABEL="Hawaii">Hawaii</OPTION>
<OPTION LABEL="Jersey">Jersey Shore</OPTION>
</OPTGROUP>
<OPTGROUP LABEL="European Cities">
<OPTION LABEL="Paris">Paris</OPTION>
<OPTION LABEL="London">London</OPTION>
<OPTION LABEL="Florence">Florence</OPTION>
<OPTION LABEL="Amsterdam">Amsterdam</OPTION>
</OPTGROUP>
<OPTGROUP LABEL="Adventure Travel">
<OPTION LABEL="Amazon">Amazon Jungle</OPTION>
<OPTION LABEL="Kenya">Kenyan Safari</OPTION>
<OPTION LABEL="Outback">Australian Outback</OPTION>
<OPTION LABEL="Galapagos">Galapagos Cruise</OPTION>
</OPTGROUP>
<OPTION>Other</OPTION>
</SELECT>
Place the opening and closing OPTGROUP tags around the related options. In this list, we set up categories for USA Beaches, European Cities, and Adventure Travel. Explorer 5.x/Win, Netscape 4.x/Win, Opera 5.01, and WebTV ignore the OPTGROUP tags and labels, but still display all the options. Netscape 6.0 shows you both the options and categories. Explorer 6.0 for Windows displays the OPTGROUP tag much like Netscape 6.0. Still, that's not exactly what the HTML 4.x standard calls for.
The textarea element represents a multi-line text field. Attributes are:
cols is the number of visible columns to display for the text area, in characters.
name specifies the name of the form field.
rows is the number of visible rows to display for the text area, in characters.
wrap="off|virtual|physical" controls word wrap at the form borders; wrap="off" (new lines will only be inserted if the user enters a carriage return) is default for Netscape; wrap="virtual" (lines will wrap at word boundaries, but actual carriage returns will not be inserted into the typed text unless the user types them) is default for Internet Explorer. wrap="virtual" is preferred by most users. wrap="physical" causes lines to wrap at word boundaries, with actual carriage returns inserted at those points, and also where a user types them. wrap is not an official attribute for textarea, so will not be validated, but is supported by most browsers (hence the different treatments).
For example:
<textarea name="address" rows="4" cols="44">
HaL Computer Systems
1315 Dell Avenue
Campbell, California 95008
</textarea>
gives this result:
The content of the textarea element is the field's initial value, but can be modified by a user. You can place formatted plain text within the <textarea> tag; this text becomes the initial value of the text area. Most browsers honor line breaks in the text, but extra spaces and line spacing may be ignored (Netscape) or honored (Internet Explorer). For this reason, keep the format of text in the text area simple. The text is often used as a way to provide instructions to the user, or as a template for further input. You cannot insert any sort of HTML tags or formatting markup; only plain ASCII text is accepted.
Typically, the rows and cols attributes determine the visible dimension of the field, and is typically rendered in a fixed-width font. HTML user agents allow text to extend beyond these limits by scrolling, as needed.
The textarea element gives visitors much more flexibility to input extended free-form text entries (comments, special shipping instructions, etc.). But before inserting a textarea box into a form, carefully optimize its display to make it easy for both you and your visitors to use. Be sure to understand the different wraps wrap="off|physical|virtual". Click this link for the full article. Note that wrap is not an official attribute of textarea in HTML 4.01, so if you use it, your HTML will not validate. wrap="virtual" wraps within the text box but sends no carriage returns, wrap="physical" wraps within the text box and sends corresponding carriage returns, "off" does not put any extra carriage returns in a text string, but sends any user input carriage returns.
An example using wrap="virtual"; compare it to no wrap specified (i.e. use browser default) in the example above:
<form action="[action]" method="post">
<textarea name="textarea name" rows="#" cols="#" wrap="off|physical|virtual">(a default can be pre-displayed)</textarea>
</form>
setting rows="4", cols="55" and wrap="virtual" gives the following text input box:
The default encoding for all forms is application/x-www-form-urlencoded. A form data set is represented in this media type as follows:
1. The form field names and values are escaped: space characters are replaced by '+', and then reserved characters are escaped; that is, non-alphanumeric characters are replaced by '%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks, as in multi-line text field values, are represented as CR LF pairs, i.e. '%0D%0A'.
2. The fields are listed in the order they appear in the document with the name separated from the value by '=' and the pairs separated from each other by '&'. Fields with null values may be omitted. In particular, unselected radio buttons and checkboxes should not appear in the encoded data, but hidden fields with VALUE attributes present should.
If you want to specify other properties of the mail message, you can add them as name/value pairs (name=value). Each property name is followed by an equal sign and a value. The list of name/value pairs is separated from the email address by a question mark delimiter (?). Name/Value pairs are separated from each other by an ampersand delimiter (&), without any extra spaces between delimiters: <mailto:OneRecipient@server.com?cc=AnotherRecipient@server.net&bcc=OneMoreRecipient@server.com&subject=Forms Survey
3. Mailto Formatter (ftp://ftp.winsite.com/pub/pc/win95/misc/mtf50_32.exe) is an excellent little freeware utility that will turn the message into 'useful to a human' format.
4. Harry Sklar has a Word macro to decode the urlencoded format at sklarnet.com/harzhelp.htm#macro.
5. If you are using mailto:, you can specify enctype="text/plain" to get a plain text email response.
If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
To process a form whose action URL is an HTTP URL and whose method is POST, the user agent conducts an HTTP POST transaction using the action URI, and a message body of type application/x-www-form-urlencoded format as above.
You can use cookies to prevent duplicate/multiple form submission; see the Use Cookies To Stop FORM Submission Duplicates section.
Consider the following document:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>Sample of HTML Form Submission</title>
<h1>Sample Questionnaire</h1>
<p>Please fill out this questionnaire:
<form method="post" action="http://www.w3.org/sample">
<p>Your name: <input name="name" size="48">
<p>Male <input name="gender" type="radio" value="male">
<p>Female <input name="gender" type="radio" value="female">
<p>Number in family: <input name="family" type="text">
<p>Cities in which you maintain a residence:
<ul>
<li>Kent <input name="city" type="checkbox" value="kent">
<li>Miami <input name="city" type="checkbox" value="miami">
<li>Other <TEXTAREA name="other" cols="48" rows="4"></textarea>
</ul>
Nickname: <input name="nickname" size="42">
<p>Thank you for responding to this questionnaire.
<p><input type="submit"> <input type="reset">
</form>
The initial state of the form data set is:
name ""
gender
"male"
family ""
other ""
nickname
""
Note that the radio input has an initial value, while the checkbox has none.
The user might edit the fields and request that the form be submitted. At that point, suppose the values are:
name "John Doe"
gender
"male"
family "5"
city "kent"
city "miami"
other "abc\ndef"
nickname
"J&D"
The user agent then conducts an HTTP POST transaction using the URI http://www.w3.org/sample. The message body would be (ignore any line breaks):
name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D
Most Web pages use forms for inputting user information, and this is usually the best way to gather necessary user data. But there are certain flaws with this method of information gathering. In order to prevent users from submitting bad data, there must be a validation of the field values before the data is sent to the server.
Form validation is the checking process that occurs before the actual submission of the form. If the data passes the validation, the code formats the data and then submits the form. If the form data fails any part of the validation test, the user is prompted with an error message, asked to correct the error, and asked to submit the form again.
To ensure that the code works with all browsers, you will want to write all client-side code in JavaScript. The following form validation routine involves string checking and can be expanded upon, after you check the fields for value or length, by adding more specific data checking.
For select elements, check the index value, and for text fields, check for empty strings. This simple routine can handle as many elements as you need by adding more variables and value comparisons. When the user presses the submit button, the form data is checked to make sure that all of the required fields have appropriate values. This is achieved by adding a function call to the form tags onSubmit event as shown below:
<form method="POST" onSubmit="return validateInput(this)">
The validation function code:
<SCRIPT LANGUAGE="JavaScript">
<!--Begin
function validateInput() {
var PT=document.form.Type.value;
var APC=document.form.Category.value;
var Errmessage = "You are required to complete the following fields: ";
if (PT<1) {
Errmessage = Errmessage + " - Type";
}
if (APC=="") {
Errmessage = Errmessage + " - Category";
}
//alert if fields are empty and cancel form submit if (Errmessage == "You are required to complete the following fields:
") {
return true;}
else {
alert(Errmessage);
return false;
}}
// End -->
</SCRIPT>
Because the textarea elements do not have length constraints, it's important to check them for proper data length as the user enters the information into the form. This is achieved by adding a call to a textLimit validation function in the element's onKeyUp event as shown below:
<textarea cols="50" rows="2" value="" name="txtRemarks" onKeyUp="textLimit(this.form.txtSchedRemarks,100);" id="txtRemarks"></textarea>
The validation function code:
<SCRIPT LANGUAGE="JavaScript"> <!-- Begin textLimit routine to limit the number of //characters in a field.
function textLimit(field, maxlimit) {
if (field.value.length > maxlimit){
// if too long...trim it!
field.value = field.value.substring(0, maxlimit); alert('You have exceeded the size limit of ' + maxlimit + ' for this entry field.');} //all alert text on one line.
}
// End -->
</SCRIPT>
For additional validation and formatting routines, visit the JavaScript Source.
If the submit button on your form isn't properly placed within the FORM tag, the form won't send properly. Don't let this simple HTML error frustrate your visitors.
If you use a WYSIWYG HTML editor such as Front Page, you probably won't find this problem until you actually begin to test your form in a browser. The following code displays perfectly in some editors' preview options even though the INPUT control is outside the FORM tag:
<form method="post" name="testForm" action="enter URL address here">
Name: <input type="text" name="name" size="20">
<br>
Email: <input type="text" name="email" size="35">
<br>
</form>
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset">
Explorer will display the Submit and Reset buttons, but won't process the commands. When you press the Submit button to send the information, you'll wait and wait and wait - and nothing will happen. Netscape is more unforgiving and won't display the buttons at all. Both Netscape and Explorer display the information differently, but neither actually submits the information.
if you want your visitors to be able to submit information to you, be sure your INPUT tag is properly placed with the other controls inside your FORM tag. NetMechanic's HTML Toolbox makes this task easy: it analyzes and identifies many coding errors that can affect your Web page's display and functionality.