Lesson 5

Forms

This is the final (and also the longest) lesson in this tutorial. You now have all the skills you need to create functional web pages. When you combine these skills with Cascading Style Sheets, these functional pages will also develop visual appeal. With your knowledge of links, you can create a degree of interactivity for the user.

Forms take that interactivity a great deal further. They allow you to collect information from people visiting your web pages. Forms enable you to gather just about any kind of information which can then be processed by a server-side script, or imported into other applications for analysis. There are many form elements to play with, so this will be a long lesson!

What's in a form?

A form is part of a web page that you create using XHTML elements. It is enclosed within a form element, and it contains special controls, such as buttons, text fields, check boxes, submit buttons, and menus. Collectively, these elements combine to create a sort of user interface for the form. The user can fill out the form and submit the data in a manner that you specify.

Once this data has been submitted, several things happen. First, the form identifies the controls within that form containing data and builds a form dataset to contain it. Next, the dataset is encoded and sent to the web server to be processed. It is extremely important that you understand the implications of that last step. After the user has clicked the “Submit” (or similar) button, the process is no longer handled by pure XHTML and becomes reliant upon a script of some kind.

What's a script then?

Scripts are pieces of code that have been written in a scripting language that executes on the web server. The most popular languages for these scripts include PHP, Perl, and ASP.

There are three exceptions to this rule. Firstly, the form can be used to redirect the user to a new web page, based on their input. Secondly, the form data can be emailed (unformatted) to you. This method provides you with a useful mechanism to test your form. Finally, forms are sometimes used in Dynamic HTML (also called DHTML), because they can be used to trap user events like mouse clicks.

It is beyond the scope of these tutorials to explain either server-side scipting or DHTML in any detail. I will give a script example towards the end of the lesson, written in PHP, which can be adapted to process simple form data and email it to you.

Form Elements

form
This element encloses a form. It includes information about how and where the data collected gets processed.
fieldset
You can group related form controls and labels within this element.
legend
This element provides a caption for a fieldset element.
label
You can attach information about a form control with this element. Its for attribute refers to the control it is describing.
input
This is the most versatile form control, with 10 different options.
select
This element encloses the choices available in a menu.
option
Each option available within a select menu is contained within this element.
textarea
This control offers multi-line text input.

The following example includes most of the controls described above, so it is a rather large chunk of code. It is called form_example.html if you want to see it in the source code:

<form method="get" action="#">
  <fieldset>
    <legend>Some Input Controls</legend>
    <p><label for="control1">Control 1: <input type="text" id="control1" name="control1" size="20" /></label></p>
    <p><label for="control2">Control 2: <input type="text" id="control2" name="control2" size="20" value="Value in here" /></label></p>
    <p><label for="control3">Password:  <input type="password" id="control3" name="control3" size="20" /></label></p>
    <input type="hidden" name="secret" value="Hidden information can be passed" />
    <fieldset>
      <legend>Radio Buttons</legend>
      <p>What does XHTML stand for?<br />
        <label for="control4">
          <input type="radio" id="control4" name="xhtml" value="Extendable" /> Extendable Hypertext Markup Language
        </label><br />
        <label for="control4">
          <input type="radio" id="control5" name="xhtml" value="Expandable" /> Expandable Hypertext Markup Language
        </label><br />
        <label for="control6">
          <input type="radio" id="control6" name="xhtml" value="Extensible" /> Extensible Hypertext Markup Language
        </label>
      </p>
    </fieldset>
    <p>
      <label for="control7">
        Type your comments in here:<br />
        <textarea id="control7" name="control7" rows="5" cols="30"></textarea>
      </label>
    </p>
    <fieldset>
      <legend>Checkboxes</legend>
      <p>Check any of these that you like:<br />
        <label for="control8">
          <input type="checkbox" id="control8" name="control8" value="Candy" /> Candy
        </label><br />
        <label for="control9">
          <input type="checkbox" id="control9" name="control9" value="Pizza" checked="checked" /> Pizza
        </label><br />
        <label for="control10">
          <input type="checkbox" id="control10" name="control10" value="Fries" /> Fries
        </label>
      </p>
    </fieldset>
    <p>
      <label for="control11">
        More comments:<br />
        <textarea id="control11" name="control11" rows="5" cols="30" disabled="disabled">This control is disabled!</textarea>
      </label>
    </p>
    <fieldset>
      <legend>Submission Controls</legend>
      <p>
        <label for="control12">
          Submit this form with an image:<br />
          <input type="image" id="control12" src="http://www.w3.org/Icons/valid-xhtml10" value="Submit me!" />
        </label>
      </p>
      <p>
        <label for="control13">
          Submit this form with a submit button:<br />
          <input type="submit" id="control13" value="Form was submitted with a submit button" />
        </label>
      </p>
      <p>
        <label for="control14">
          Reset the form to its initial state:<br />
          <input type="reset" id="control14" />
        </label>
      </p>
    </fieldset>
  </fieldset>
</form>

Viewed in a browser, you should see the following:

The form element

Like paragraphs and headings, forms are block-level elements. The opening <form> tag will always be preceeded by a line break. You cannot nest forms; however, you can have more than one form on a page. You can keep them separate by giving them name attributes with different values.

The syntax for creating the form element is fairly simple. The two most commonly used attributes are action and method. Both of these attributes are optional. Here is an example of the typical usage of a form element:

<form method="get or post" action="some action">
  Content, form controls and other XHTML elements
</form>

The action attribute defines the action taken when the form is submitted, and it usually contains a URL for a server-side script on the web server. If you leave out the action attribute, the form data will be submitted to the current URL (in otherwords, the page containing the form). This doesn't seem very useful, but it would be if the page with the form carried the processing script within it. The action attribute can also be set to link to another web page or a mailto link. The latter is formed as follows:

<form method="post" action="mailto:somebody@isp.com" enctype="text/plain">

That will attach the form data set to an email (unformatted), which is then sent to the email address listed in the action attribute. I recommend using this method to test forms, since you can email the results to yourself by using your own email address! I do not recommend doing this for anything beyond testing.

The input element

The input element consists of an opening tag with attributes, no other content and no closing tag. A forward slash is added to comply with the XHTML specifications:

<input attributes />

There are several attributes to the input element, the most important of which is type. Apart from submit and reset buttons, all form controls must have a name attribute, which carries the name that the control's data is assigned to. That name is usually referred to as a variable, or if there is more than one value, an array.

Text controls enable you to gather information from a user in small quantities. This control type creates a single-line text input field in which users can type information, such as their name. Here is an example of a text control that asks for the user's name:

<p>Please enter your name below:<br />
<input type="text" name="UserName" size="30" /></p>

The text control created will hold the user's name in a variable called UserName. The size attribute sets the width of the text control in characters, in this case 30.

Sometimes you may wish to limit the number of characters a user can type into the text control. This can be achieved by adding the maxlength attribute, as seen in the example below:

<p>Please enter your email address below:<br />
<input type="text" name="Email" size="30" maxlength="30" /></p>

The user will be unable to type more than 30 characters into the text box. The value of maxlength has no effect on the size attribute.

Another useful attribute is the value attribute. It allows you to put a value into the text control that can be modified by the user:

<p>How old are you?<br />
<input type="text" name="Age" value="age?" /></p>

It may be necessary to create a read-only text control. This will prevent users from entering text into the control. This is useful when some elements of the form are prepopulated, and you want the user to see the value without actually being able to change it:

<p>The year is:<br />
<input type="text" name="Year" value="2002" readonly="readonly" /></p>

The password control is very similar to the text control. The only real difference is that the user's input is masked with asterisks (or some similar character):

<p>Enter your password below (5 characters only):<br />
<input type="password" name="UserPswd" maxlength="5" /></p>

Important! When data entered into a password field is sent to the server, it is not encrypted in any way. Therefore, this is not a secure means of transmitting sensitive information. Although the users cannot read what they are typing, the password control provides no other security measures.

You use a submit control to transmit the form data in the manner specified in the form element. Entering submit as the type of control creates a submit button with the default label of "Submit Query":

<input type="submit" />

By using the value attribute, you can alter the text displayed on the button:

<input type="submit" value="Ooh! Press me!" />

You can also specify a name attribute. Setting it to "action" will send the value of the value attribute to the server along with the form data. It allows you to have more than one submit button, each performing a different action. For example:

<input type="submit" name="action" />
<input type="submit" value="Edit Fields" name="action" />

The reset button clears the contents of the form and sets all the form controls to their default values. Be warned: All the fields are cleared, so you may wish to warn the user by entering something into the value attribute. The first example is the default button, the second is more helpful to the user:

<input type="reset" />
<input type="reset" value="Clear ALL Fields" />

Check boxes are very handy when you want to give the user a "toggle" that reflects an on or off state. They are very easy to create:

<p>Check the box to receive spam <input type="checkbox" name="spam" /></p>

You can create a default value of "checked" by adding the checked attribute, and you can also group check boxes together and assign them the same control name. This allows multiple values to be assigned to one property:

<p>Are you ill? <input type="checkbox" name="ill" checked="checked" /></p>
<p>Describe your symptoms:</p>
<p><input type="checkbox" name="symptoms" value="nausea" /> Nausea?<br />
<input type="checkbox" name="symptoms" value="lighthead" /> Light-headedness?<br />
<input type="checkbox" name="symptoms" value="headache" /> Headache?<br />
<input type="checkbox" name="symptoms" value="fever" /> Fever?</p>

Radio buttons are almost identical to check boxes, but the browser renders them slightly differently. The value attribute is mandatory. Here's a quick example:

<p>Do you agree?<br />
<input type="radio" name="agree" value="Yes" /></p>

They really come into their own, however, when you have two or more radio buttons sharing the same control name, because they form a mutually exclusive data set. In otherwords, only one radio button can be selected:

<p>What is your gender?<br />
Male <input type="radio" name="sex" value="Male" checked="checked" /><br />
Female <input type="radio" name="sex" value="Female" /></p>

I hate graphical buttons, but they do have one useful feature. When a user clicks the button, the x and y coordinates of the point the user clicked are transmitted to the server along with the form data. This could be useful if the image used was a map and you wanted the user to click the map to supply you with coordinates.

The syntax for a graphical button is much the same as any other. Here is an example:

<input type="image" src="http://www.w3.org/Icons/valid-xhtml10" name="SubmitButton" alt="Click to Submit" />

The alt attribute is usually associated with the img element. Any of the attributes that would normally associate with the img will happily work with the "image" type form control. In that example, the result submitted to the server might look like this:

SubmitButton.x=32&SubmitButton.y=25

If the name attribute had been left out, the coordinates returned would just be:

x=32&y=25

You can create buttons that will be used to execute client-side scripts. Here is an example:

<input type="button" name="verify" value="Verify Data" onclick="verifydata()" /> 

The example above creates a button that runs a script called verifydata when it's clicked. Such a script might reside in the head element, and be written in JavaScript.

Hidden controls are not seen by the user, nor can they be modified by the user. When the user submits the form, the value assigned to the hidden control is sent along with the other data. In the next example, the value "Number 6" is given to the variable "Identifier":

<input type="hidden" name="Identifier" value="Number 6" />

The textarea element

Sometimes you just need something bigger, eh? XHTML has an element called textarea that functions in a similar way to a text box. This element has no limit on the amount of text that can be typed in it. The size of the area is specified by using the cols and rows attributes. The unit of measurement for these attributes is characters. Leaving out these attributes will cause the browser to use its default size, which varies from browser to browser.

The most common use for a textarea is a "comments" area on a contact form. I will disuss a contact form later in the lesson, as this is a common use of forms and will make a good example. Here's the code for a typical textarea. You will notice that this element has an end tag.

<p>Please enter your comments in the area provided below:<br />
<textarea name="comments" rows="10" cols="40">Put your comments in here</textarea>

Notice how the “Put your comments in here” text did not need to be entered in as a value attribute. This is because the element has an end tag.

The select element

Using the select element, you can create a menu (or list box) that contains choices for the user. This box can either be of the "drop-down" or "scollbar" type. By itself, select only defines how a menu will appear. You must include option or optgroup elements to create the menu. In the next example, a drop-down menu is created that allows the user to choose from a list of continents:

<p>Pick a continent:<br />
  <select name="continent">
    <option>Africa</option>
    <option>Asia</option>
    <option>Europe</option>
    <option>North America</option>
    <option>Oceania</option>
    <option>South America</option>
  </select>
</p>

You can turn it into a scrollbar menu with the simple addition of a size attribute. Setting the value to less than the number of options causes the scrollbar to appear:

<p>Pick a continent:<br />
  <select name="continent" size="3">
    <option>Africa</option>
    <option>Asia</option>
    <option>Europe</option>
    <option>North America</option>
    <option>Oceania</option>
    <option>South America</option>
  </select>
</p>

Example contact form

We will create an example of a simple contact form. There are two parts:

  1. The XHTML form.
  2. The PHP mail handler.

The XHTML form will collect the data. Once the submit button has been clicked, this data will be sent to the PHP mail handler, where the data will be formatted and emailed to the author.

The XHTML form

You can find this in the source code, as contact.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Contact</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  </head>
  <body>
    <form method="post" action="mail.php">
      <dl>
        <dt><label for="username">What is your name?</label></dt>
        <dd><input type="text" id="username" name="username" size="40" /></dd>
        <dt><label for="email">What is your email address?</label></dt>
        <dd><input type="text" id="email" name="email" size="40" /></dd>
        <dt><label for="how">How did you learn of my website?</label></dt>
        <dd>
          <select id="how" name="how">
            <option>Been here before</option>
            <option>Search engine</option>
            <option>Link on a website</option>
            <option>Link on newsgroup or forum</option>
            <option>Mind your own business!</option>
            <option>Other</option>
          </select>
        </dd>
        <dt><label for="comment">Do you have any questions or comments?</label></dt>
        <dd><textarea id="comment" name="comment" rows="5" cols="50"></textarea></dd>
      </dl>
      <p><input type="submit" value="Send" /></p>
    </form>
  </body>
</html>

Viewed in a browser, you should see the following:

The form above gathers user's name (username), email address (email), details about how they found your site (how), and comments (comment). It sends the information to a form handler called mail.php that resides in the same directory.

The PHP mail handler

Please note: The mail handler (mail.php) will only run on a web server that is running the PHP interpreter. You may not be able to test this script unless you upload the form and the .php file to a remote server. This is a very basic script that offers no form of error checking. It is unsuitable for actual web deployment:

<?php

// redirect script to form if the form was not submitted
if($_POST['submit'] != "Send") {
  header("Location: contact.html");
  exit;
}

// create global variables of post data
extract($_POST);

// prepare and send email
$to = "example@example.com";
$subject = "XHTML Tutorial form feedback";
$message = "Name: $username\n";
$message .= "Email: $email\n";
$message .= "How they found the site: $how\n";
$message .= "Comments: ".stripslashes($comment);
mail($to, $subject, $message) or die("Email could not be sent");

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Thank You</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  </head>
  <body>
    <h1>Thank You</h1>
    <p>The form has been successfully submitted. Would you like to <a href="contact.html">return to the form</a> or <a href="/simon/xhtml_tutorial/">go to the lesson home page</a>?</p>
    </form>
  </body>
</html>

Once the user has submitted the form, the email is sent to example@example.com and the user is thanked. The user is given a choice to either return to the form, or go to the home page of this tutorial.

That's all, folks!

That brings us to the end of the XHTML tutorial. Thank you for your patience. Needless to say, this has been a very rough and ready tutorial that has really only given you the basics of this markup language. I hope you have enjoyed as much as me. If you have any questions (or if you spot any errors), please don't hesitate to contact me.

Note: This tutorial was originally written in early 2002. The last revision (a major overhaul, actually) was in early 2006.