HTML and CSS  Home HTML and CSS Tutorials All About Forms
rss

All About Forms

Author: HtmlCodeTutorial More by this author


Forms are the most popular way to make web pages interactive. Like forms on paper, a form on a web page allows the user to enter requested information and submit it for processing. (Fortunately, forms on a web page are processed much faster.)

Let's look at a very simple form:

this code

<FORM ACTION="/cgi-bin/mycgi.pl"> favorite color: <INPUT NAME="color"> </FORM>

produces this

favorite color:

This form has all the required elements for a form:
<FORM ACTION="/cgi-bin/mycgi.pl">
Start the form here. The ACTION attribute, which is required with every <FORM ...> tag, is used to set what happens when the form is used e.g send the results to given page.

<INPUT NAME="color">
Data entry field. <INPUT ...> creates most types of form fields, but <TEXTAREA ...> and <SELECT ...> also create certain types.

</FORM>
End the form here.

Of course, this form doesn't do much. You can type something into the one field, but that's it, nothing happens from there.

Forms and CGI

The original and still most popular use for forms is in conjunction with CGI (Common Gateway Interface). In the CGI way of doing things, the data the user enters is sent to the web server, where a program processes the data and returns the results. In other words, all the data is processed on the server, not in the web browser.

Let's expand our earlier example to show how to incorporate CGI:

<FORM ACTION="/cgi-bin/mycgi.pl">
favorite color: <INPUT name="favecolor">
<INPUT TYPE=SUBMIT VALUE="Submit">
</FORM>

which gives us

favorite color:

Here's what the new pieces mean:

<FORM ACTION="/cgi-bin/mycgi.pl">
ACTION tells the browser where to send the data for processing (more on that shortly). ACTION is required with every form, even forms that don't use CGI.

<INPUT name="favecolor">
We've added the NAME attribute. NAME identifies each field, "names" it so it can be referred to later.

<INPUT TYPE=SUBMIT VALUE="Submit">
This <INPUT ...> tag creates the "submit" button, which the user presses to send the form to the web server.

That's the basic set up for a CGI form, but what happens after the user presses Submit? Consider, for example, this simple form:

Join our mailing list
Name:
E-mail:

Here's the chain of events when the user hits "Submit":

Submit

  1. When the user presses Submit, the browser sends the form data to the web server.
  2. The web server launches the CGI program which was written to process this form.
  3. The CGI program does whatever it does with the data. The program might consult a database, perform calculations on the data, use the data to add the user to a mailing list, whatever the programmer wants it to do. Whatever else the program does, it generates a web page using HTML so the user can see the results of submitting the form.
  4. The CGI program passes the HTML back to the web server.
  5. The web server passes the HTML back to the browser.

So there are three pieces to the CGI process: the form on your web page, the web server, and the CGI program. This guide deals with the first part: how to use HTML to make a form. Your web administrator handles the web server, and for a good guide on how to write CGIs, we recommend James Marshall's excellent (and short) CGI Made Really Easy.

Technically speaking there is no such thing as "a CGI". "CGI" is a standard protocol, not an actual implementation. However, it has become common to refer to a program which uses the CGI standard as "a CGI", and we will follow that custom here.

One of the reasons CGI is so popular is that the CGI program can be written in just about any programming language: C, C++, Perl (the most popular language for CGI), Visual Basic, etc. CGI was designed to allow great flexibility in processing the form data, while still allowing the results to be returned as HTML (or other formats, but HTML is the most popular).

Forms Working With Scripts


Until scripting for web pages came along, CGIs were the only way to process form data. Now that Javascript is available on most web browsers, scripting provides a whole new avenue of neat ways to use forms. Unlike with CGI, forms that use scripts process the information immediately and can return the results right to the current web page. Script-based forms can also react to events other than just the user pressing a "Submit" button.

An example of a script-only form is small form which sets the color of the current web page (works with IE5+ but not some other browsers):

This code

<FORM>
<SELECT onChange="document.bgColor=this.options[this.selectedIndex].value">
<OPTION VALUE="FFFFFF">White
<OPTION VALUE="FF0000">Red
<OPTION VALUE="00FF00">Green
<OPTION VALUE="0000FF">Blue
</SELECT>
</FORM>

Produces background colour selected in listbox

Automatically Putting the Cursor in a Field

name:

email:



This page demonstrates a technique for automatically putting the cursor into an input field as soon the page is loaded.

Let's suppose you want the user to go directly to the following form. Notice that we set the names for the form and the field.

<FORM NAME="MyForm" ACTION="../cgi-bin/mycgi.pl">
name: <INPUT NAME="realname"><BR>
email: <INPUT NAME="email"><BR>
<INPUT TYPE=SUBMIT VALUE="Submit">
</FORM>

We can set the focus immediately by adding an onLoad attribute to the <BODY ...> tag. Notice that the word focus must be followed by open and close parentheses: ():

<BODY onLoad="document.forms.MyForm.realname.focus()">

It's worth taking moment to consider if it's such a such a good idea to set the focus to a form field immediately. I'm always hesitant to change the default behavior of the browser. However, in some situations it makes sense, such as if your form is in a popup-window and there is little else in the popup to interact with.

Submit The Form When The User Presses Enter


Different browsers have different default behaviors about what to do when the user hits enter in a form. MSIE almost always submits the form, while Netscape will often just beep at you. Although it's usually best to leave the default browser behavior as it is, for some forms people just naturally tend to hit "enter" when they are ready. This is particularly true for login forms. With a little JavaScript we can set the form to submit on enter.

First, copy this script exactly as-is into the <HEAD> section of your document:

<SCRIPT TYPE="text/javascript">
<!--
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
    {
    myfield.form.submit();
    return false;
    }
else
    return true;
}
//-->
</SCRIPT>

For each field which should submit the form when they hit enter add an onKeyPress attribute like this:

<FORM ACTION="../cgi-bin/mycgi.pl">
name: <INPUT NAME=realname SIZE=15><BR>
password: <INPUT NAME=password TYPE=PASSWORD SIZE=10
onKeyPress="return submitenter(this,event)"><BR>
<INPUT TYPE=SUBMIT VALUE="Log In">
</FORM>

Add the attribute like it is in the example. No modification is needed. This gives us this form:

name:
password:


Restricting a Field to Alphanumeric Only

JavaScript can be used to guide the user in entering correct data. This page describes a method for restricting entered data to just letters and numbers - no spaces, commas or other types of characters are allowed. This technique is useful if you are asking for information such as a User ID which has only alphanumeric characters.

First, copy this JavaScript code into the <HEAD> section of your document:

<SCRIPT TYPE="text/javascript">
<!--
function letternumber(e)
{
var key;
var keychar;

if (window.event)
    key = window.event.keyCode;
else if (e)
    key = e.which;
else
    return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();

// control keys
if ((key==null) || (key==0) || (key==8) ||
    (key==9) || (key==13) || (key==27) )
    return true;

// alphas and numbers
else if ((("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) > -1))
    return true;
else
    return false;
}
//-->
</SCRIPT>

Using this script we can set a field as alphanumeric using the onKeyPress attribute. Use the exact onKeyPress attribute highlighted in this example. It is important that you use return in the attribute or the technique won't work.

<FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST>
User ID: <INPUT NAME=ID MAXLENGTH=8 onKeyPress="return letternumber(event)">
<INPUT TYPE=SUBMIT VALUE="go">
</FORM>

This creates this form:
User ID:

Restricting a Field to Numbers Only

The previous tutorial demonstrated a technique for restricting form field inputs to just letters and numbers. This page shows a technique for restricting the field to just numbers. The script also allows you to automatically jump to the next field if the user presses the decimal key.

First, copy this script exactly as-is into the <HEAD> section of your page:

<SCRIPT TYPE="text/javascript">
<!--
function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
    key = window.event.keyCode;
else if (e)
    key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) ||
    (key==9) || (key==13) || (key==27) )
    return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
    return true;
// decimal point jump
else if (dec && (keychar == "."))
    {
    myfield.form.elements[dec].focus();
    return false;
    }
else
    return false;
}

//-->
</SCRIPT>

Now we can create a numbers only field using the onKeyPress attribute. For our first example, we'll create a field which accepts five digits as for a United States ZIP Code. Set the onKeyPress attribute exactly like it is here:

<FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST>
U.S. ZIP Code:
    <INPUT NAME="dollar" SIZE=5 MAXLENGTH=5
   onKeyPress="return numbersonly(this, event)">
    <INPUT TYPE=SUBMIT VALUE="go">
</FORM>

This gives us this form:
U.S. ZIP Code:

Here's what happens. When the user presses a key, onKeyPress calls the numbersonly() script. numbersonly() takes two arguments: this (the input field itself), and event (the object some browsers use to check which key was pressed). numbersonly() checks if the key pressed was a number or one of the control characters such as backspace or delete. numbersonly() returns true if the key is acceptable, false if it's not. In turn, onKeyPress return the true of false value (that's why it's important to use return in the attribute) and the key is cancelled or allowed accordingly.



Rate this Material: Bad 1 2 3 4 5 Excellent
print this page tell a friend subscribe to newsletter subscribe to rss

Add comments to "All About Forms"