Friday, January 2, 2009

Example form

On this page, I have an example form and script that checks whether the user has filled in text fields and prints out the values the user filled in. Below I explain the part of the script that checks the text fields.
The example form

This is an example form. I play slightly false here: the form cannot be submitted because my present server doesn't allow CGI. Instead, I print out the values you filled in in the textarea and return false anyway, so the form isn't submitted.

The onSubmit script does two things: it checks whether you have filled in something in the four text boxes and it gathers name and value of all elements you have selected/checked and prints them out in the textarea below.
Name
Address
City
E-mail
Why do you want to learn JavaScript? Dunno
Because my boss told me to
Generally interested
It might come in useful
How did you get to this site?
I'd like additional information about oranges
potatoes
tomatoes
blue whales

When you hit 'Submit' the user input will be written to this textarea

If you want to know exactly how this script works, please see the source. On this page I'll explain only the bit that checks if the text fields are filled in.

See the Form error messages script for a superior way of informing the user of form validation problems.
Checking text fields

This script checks whether the user has filled in anything in text fields. It ignores check boxes and radio buttons, but it will always ask the user to fill in a select box, even if he has already done so, because a select box always has a value of null. So it's best to use this script only when you want to check text fields.

function checkscript() {
for (i=0;i<4;i++) {
box = document.example.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
return false;
}
}
return true;
}

In this example, I want to check elements 0-3, so I have a variable i that goes from 0 to 3. As you can see, I'm using numbers here instead of names. This is one of the cases in which it's better to use numbers than names.

for (i=0;i<4;i++) {

Then I make a variable box, which accesses the current form element. If I didn't create it, I'd have to write document.forms['example'].elements[i] a couple of times and I'm too lazy for that.

box = document.example.elements[i];

If the current text field has no value, the user has filled in nothing and we need to do several things.

if (!box.value) {

First we show an alert that uses the name of the text field. If you keep the names of your text fields logical, the user understands from this alert what text field should be filled in.

alert('You haven\'t filled in ' + box.name + '!');

As an additional service, we place the focus on the text field so that the cursor is in it and the user can start typing right away. Since all JavaScript browsers support focusing on form fields, we don't need a support detect.

box.focus()

Finally we return false. The script stops immediately and the form is not submitted. We wait for further user input.

return false;

If every text field has a value, we return true to show that everything is OK. Function stops, form is submitted and we're ready.

}
}
return true;

Introduction to Forms

On this page I give the code you need for checking user input in a form. Using these bits of code, you can write your own scripts to validate forms

I can't give you a complete script, because each form and each check are different. You'll have to use the elements I explain on this page to build your own script. I created an example form and script that you can study to get the hang of it.

On this page I discuss the limitations of using JavaScript to check a form, then I'll explain the onsubmit event handler, followed by the few methods and properties of the form itself. Then it's time for accessing the form elements and the specific syntax for accessing the user defined value of form elements.

See also Jeff Howden's excellent article Forms & JavaScript Living Together in Harmony for some of the most common usability errors and their solutions.
Limitations

First of all, you should have a clear idea of what happens when a user submits a form that has a JavaScript validation script:

1. The form is checked by a JavaScript like the one described below. If the script finds a mistake the submission is halted here. The user sees an alert and is asked to re-enter some data.
2. If nothing is wrong—or if JavaScript is disabled—the form is sent to the server and is processed by a CGI script.
3. If the CGI script finds a mistake it generates some HTML with an error message and sends it back to the user. In this case the user has to go back to the form, re-enter some values and again submit it.
4. If no mistakes are found, the CGI script does whatever it has to do with the data and directs the user to a Thank You page.

As you see, the form is checked for mistakes twice: by the JavaScript and by the CGI script. The CGI check always works, since CGI is server side. The JavaScript check only works when the user has JavaScript enabled. It follows that the CGI check is the most reliable: it always works regardless of what browser is used. Then why use a JavaScript check too?

The JavaScript check is very useful in addition to the CGI check because it can catch mistakes before the form is actually sent to the server. Thus the user doesn't have to use his back button to return to the form, something that may cause confusion, and then search for the incorrect form field, which may cause even more confusion. Therefore the JavaScript check is more user friendly than the CGI check.

In addition, when you use JavaScript the server doesn't need to spend quite so much time in error handling and is thus a little quicker. This only matters if you have lots and lots of forms, but it's good to keep it in mind.

So JavaScript is not a fail-safe method of catching mistakes, but it is very useful as an addition to CGI checks since it lightens the load on the server and is more user friendly. Therefore I recommend using both JavaScript form checks and CGI form checks. This way, you get both user friendliness and security.
onsubmit

When using JavaScript to check a form, the first thing you need is the onsubmit event handler. This event handler specifies a script that is executed when the user submits the form. That script is where you check whether certain fields have a value, whether the user has checked at least one checkbox, and any other checks you deem necessary.

The general syntax is:



where checkscript() is the name of the script. This script should return either true or false. If false is returned, the form will not be submitted. If either true or false is returned the script stops.

So the general script becomes something like:

function checkscript() {
if (some value is/is not something) {
// something is wrong
alert('alert user of problem');
return false;
}
else if (another value is/is not something) {
// something else is wrong
alert('alert user of problem');
return false;
}

// If the script makes it to here, everything is OK,
// so you can submit the form

return true;
}

Of course this function can become much more complex if you have to check a complicated form with a lot of radio buttons and things. The general idea remains the same, however: You go through the elements, check whatever you want to check and as soon as you find any mistake, you return false, after which the script stops and the form is not submitted.

Once you've found a mistake, you should notify the user of the problem. This used to be done by an alert, but nowadays you can generate error messages and insert them next to the form field.

Only at the very end of the script, when you have checked all elements and encountered no mistakes, you return true, after which the form is submitted.
Form methods and properties

JavaScript has a few built-in methods and properties for dealing with forms. Three of them are especially important:

You can submit a form by using the submit() method. To submit the first form on the page, do

document.forms[0].submit()

Please note that when a form is submitted by JavaScript the onsubmit event handler is never executed.
To reset the form, do

document.forms[0].reset()

I assume, but have not tested, that the onreset event handler isn’t executed either if you reset the form through JavaScript.

Finally, you can change the ACTION of a form if you want to:

document.forms[0].action = 'the_other_script.pl';

This can come in very handily if a form has to be submitted to another script in some cases.
Accessing the form elements

The form validation script needs to access the form in the HTML page to determine what values the user has filled in. So first we have to enter the form by means of the Level 0 DOM. The general syntax for accessing a form element is:

document.forms[number].elements[number]

When the page is loaded, JavaScript makes an array forms in which it puts all the forms that are on the page. The first form is forms[0], the second is forms[1] etc.

Each form has another array in which JavaScript puts all the elements in the form. The first elements is elements[0], the second elements[1] etc. Every ,