Using JavaScript To Control Forms - Part 1

This tutorial explains some of the JavaScript techniques that can be used to improve HTML forms. There are many techniques, mainly based on validating form fields, including checking that a field has been filled in, and that it contains the right kind of data. Other techniques provide responsive and intelligent forms that can add or remove options as questions are answered, or simply improve general appearance.

This is Javascript for IE5.

The primary purpose of forms is to provide a neat and efficient method for collecting and transferring information. This information can be readily converted into machine-readable data, and then stored and used. All this activity generally takes place on a server, using CGI (Common Gateway Interface) programming. (See the CGI Tutorial)

The two problems at the form entry stage are people supplying garbage information, and people needing assistance when filling out a poorly designed form.

Before we examine the actual implementations of JavaScript to improve forms, let's look briefly at using HTML forms.

HTML Forms
Forms are special HTML container elements. They have two features that distinguish them from other HTML elements:

  • They contain <INPUT> elements (and other elements) which provide spaces for a user to provide information.
  • The information in a form can be collected and sent somewhere.

There are ten <INPUT> elements, defined through the TYPE attribute.

BUTTON CHECKBOX FILE HIDDEN IMAGE
PASSWORD RADIO RESET SUBMIT TEXT

Only <INPUT> elements with NAME/VALUE attributes will be sent, with the exception of the SUBMIT and RESET buttons. Also, the VALUE attribute for the TEXT element is the actual text entered, and therefore does not need to be set by the programmer.

There are other elements that can supply data for a form, for example <SELECT> and <TEXTAREA>. These elements are not types of the INPUT element and are eleborated on in the form tutorial.

The information is sent to the address defined in the ACTION attribute of the <FORM> element. The <FORM> element has another attribute, METHOD, which defines the type of posting used. There are two types - GET and POST. GET is used for some CGI programs, but POST is the better method.

GET is the default METHOD value, and results in extended URLs like: URL?Name=Jon&Surname=Perry

For small-scale operations, the address to send to is usually an email address, and each form is parsed individually when it arrives. This is not normally too much work, especially if you make the form element names clear in meaning (this can be simplified by using the HIDDEN type of the INPUT element).

For people with a CGI application to parse the forms, the address to send to is usually the URL of the CGI application on a server. This then does any remaining work.

This tutorial relates to forms before all the processing takes place, while the user is still supplying input to the form.

Example
An example of an HTML document with a form is:

<HTML>
<HEAD>
<TITLE>What's your name?</TITLE>
</HEAD>
<BODY>
<FORM ACTION="http://hoohoo.ncsa.uiuc.edu/cgi-bin/post-query" METHOD="post">
<INPUT TYPE="TEXT" NAME="Name">What's your name?
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>

This code demonstrates the key features of a form. The URL is a URL at the National Center for Supercomputing Applications that takes any form you care to send it and processes it into an HTML document, then displays the document. Not very useful (and it interferes with our normal operations) but it does allow you to see a CGI program in action.

A normal, email-based form with slightly more <INPUT> elements, and better form presentation follows. Before you execute this program, change the email address to your own.

<HTML>
<HEAD>
<TITLE>Name and Sex?</TITLE>
</HEAD>
<BODY>
<FORM ACTION="mailto:yourname@youraddress.com" METHOD="post">
<INPUT TYPE="TEXT" NAME="Name">Please enter your name
<BR>
<INPUT TYPE="RADIO" NAME="Sex" VALUE="Male">Male
<INPUT TYPE="RADIO" NAME="Sex" VALUE="Female">Female
<BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>

This code sends the form to the email address you entered.

When the code is first loaded, the sex radio boxes are blank. It would be rude to suggest a sex as a priority - although you would be right 50% of the time - and so I have left it blank. This raises the problem that someone might submit the form with the sex radio boxes still blank, and we will create a solution for this later on.

When a form arrives, you may be surprised at its file extension, and initially you may be unable to open the file. The data file is basically a text file, and can be opened (and associated) with NotePad or WordPad.

Next we will look at a few simple JavaScript techniques that we can use to improve a form, beginning with making sure fields that we definitely need are filled in.

Required Fields
A required field in a form is a field that MUST have at least some content before the form will be processed. If the form is an order form, partial information may be useless. Other circumstances also occur where partial information is insufficient.

Please note that this technique does not prevent spurious input such as @~@@!!.

The following code demonstrates a Required Field in action - the name must have some content for the form to be sent. Substitute your own domain CGI details to receive the form.

<HTML>
<HEAD>
<TITLE>Required Fields</TITLE>
<SCRIPT>
function validate() {
mNv=mainform.Name.value;
if (mNv=='') {
alert('Your name is a required field. Please try again.');
event.returnValue=false;
}
if (!(mainform.Sex[0].checked || mainform.Sex[1].checked)) {
alert('Your sex is a required field. Please try again.');
event.returnValue=false;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="mainform" ACTION="http://yourdomainhere/cgi-bin/post-query" METHOD="post" onsubmit="validate();">
<INPUT TYPE="TEXT" NAME="Name" >Please enter your name (required)
<BR>
<INPUT TYPE="RADIO" NAME="Sex" VALUE="Male">Male
<INPUT TYPE="RADIO" NAME="Sex" VALUE="Female">Female
<BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>

The form section is pretty much as usual for a form, except for two necessary additions, the addition of the NAME attribute:

NAME="mainform"

and the onsubmit event handler:

onsubmit="validate();"

This event handler ensures that when we submit the form, we get diverted to the internal JavaScript function validate(), which in this case validates the form against any easy-to-remedy problems, namely empty fields.

The JavaScript validate() function holds routines for checking individual form elements, and it checks them against 'illegal' inputs. It is 'illegal' to provide either no name or no sex with this form. 'Illegal' means that a form with either of these fields empty breaks our 'law' for a satisfactory form.

In this case, validate() checks for both an empty Name field, and an empty Sex radio selection.

The first sub-section of the validate() function examines the Name field of the form mainform. If the field is empty when the form is submitted, then we detect this, tell the viewer the bad news and reject the form.

mNv=mainform.Name.value;
if (mNv=='') {
alert('Your name is a required field. Please try again.');
event.returnValue=false;
}

Setting the returnValue property of the event object to false rejects the form. This action cancels the onsubmit event, and prevents the event from reaching the actual mechanism that physically sends the form over the Internet.

The second sub-section checks that a Sex radio box has been selected. This code uses advanced logic techniques. Again, if we find no Sex radio box selected, we notify the viewer, ask them to try again, and reject the form.

if (!(mainform.Sex[0].checked || mainform.Sex[1].checked)) {
alert('Your sex is a required field. Please try again.');
event.returnValue=false;
}

A brief explanation of the logic involved goes like this:

We can detect whether a radio box is selected (checked) by looking at its checked property.

mainform.Sex[0].checked is true if the first Sex radio box is selected. Remember that radio boxes offer a one-from-many choice, and so only one of the Sex radio boxes may be selected.

The logic for the code works out that if either Male or Female is selected, then (mainform.Sex[0].checked || mainform.Sex[1].checked) is true. If neither is selected, then this expression is false. This is the only situation in which the expression is false, due to the nature of the || (or) statement.

The if statement compiles if a condition is true, and so we must negate the entire thing. This gives the following logic table:

Sex[0].checked Sex[1].checked Sex[0] || Sex[1] !( Sex[0] || Sex[1])
false false false true
true false true false
false true true false
true true Can't happen Can't happen

For more complicated radio boxes, the situation might get beyond control. Fortunately there are other techniques we can use. The first is to set a radio box to checked to begin with. This completely removes the need for a validating routine.

<INPUT TYPE="RADIO" NAME="Sex" CHECKED>Male
<INPUT TYPE="RADIO" NAME="Sex">Female

Although you may be wrong, and favour one sex over the other, you have saved some coding.

But say you wanted to determine a larger selection of radio choices without offering some kind of opinion on the 'typical' option. This scenario risks a blank radio field being submitted, and this is what we want to avoid.

Validating Large Radio Fields
By a large radio field, I mean three or more connected radio boxes. The above method for dealing with two radio buttons is as good if not better than this code for two radio buttons.

The idea of this code is to find if any radio boxes are selected inside a for loop. If they are, then we are happy, and we can proceed. If not, then we must reject the form - a required field has not been filled in correctly.

<HTML>
<HEAD>
<TITLE>Validating Large Radio Fields</TITLE>
<SCRIPT>
function validate() {
ICOK=false;
for (ic=0;ic<5;ic++) {
if (mainform.IceCream[ic].checked) ICOK=true;
}
if (!ICOK) {
alert('Your favorite Ice Cream flavor is a required field. Please try again.');
event.returnValue=false;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="mainform" ACTION="http://yourdomainhere/cgi-bin/post-query" METHOD="post" onsubmit="validate();">
<BR>
<INPUT TYPE="RADIO" NAME="IceCream" VALUE="Vanilla">Vanilla
<INPUT TYPE="RADIO" NAME="IceCream" VALUE="Choc">Chocolate
<INPUT TYPE="RADIO" NAME="IceCream" VALUE="Straw">Strawberry
<INPUT TYPE="RADIO" NAME="IceCream" VALUE="RaspR">Raspberry Ripple
<INPUT TYPE="RADIO" NAME="IceCream" VALUE="Mint">Mint
<BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>

This code creates an ICOK variable - which means IceCreamOKay. This is set to false, and if the viewer has selected a favorite icecream flavor, then the ICOK variable becomes true.

for (ic=0;ic<5;ic++) {
if (mainform.IceCream[ic].checked) ICOK=true;
}

If ICOK is still false, then no favorite was selected, and the viewer must be prompted to try again.

if (!ICOK) {
alert('Your favorite Ice Cream flavor is a required field. Please try again.');
event.returnValue=false;
}

And that is it for now. The next tutorial in this series will extend this theory into using various other validating techniques - including using Regular Expressions to ensure correct input, validating a SELECT element and using JavaScript pre-processing on forms, and submitting additional and processed information through HIDDEN elements.

Using JavaScript to Control Forms - Part 2
Using JavaScript to Control Forms - Part 3