Getting data from forms

When JavaScript is applied to a HTML page it creates a document object. It is through this object that JavaScript can access and manipulate elements of the HTML page, one aspect of this that is covered elsewhere is the document.getElementById() method.

The Document Object Model (or DOM) is a model which describes how each element in the document object relates to it. An important aspect of the DOM is the forms array. Each document which contains forms has an entry in the forms array for each form it contains (after all a HTML page can contain more than one form). Each entry in the forms array contains another array containing all the elements within the form. These objects are very handy for extracting and verifying data entered by the client with JavaScript.

Ordinarily working through forms objects using array references is a bit awkward. Have a look at the example below:

// this will extract the entered value in the 3rd element 
// of the first form on the page
var myVariable = document.forms[0].elements[2].value;

Rather than keeping track of the order of these elements it is much easier to name the <form> tag and to name the <input> tags it contains. For example if we have this form to work with ...

<form name="mailform" action="#" method="get" id="mailform">
   <label for="phone">Telephone:</label>
   <input name="phone" type="text" />
</form>

... the line of javascript can be modified to the following:

// this will extract the entered value in the 3rd element 
// of the first form on the page
var myVariable = document.forms.mailform.phone.value;

This is much easier to read!

Live example

Add some data to the telephone entry field below and click the "Check Value" button.

Other types of form control (checkbox, radio button, select list)

The technique explained above will only work where form fields allow the typing in of text data, so <input type="text" ... /> and <textarea> will work but checkboxes, radio button and select boxes will not.

Here are a list of resources which explain the differing methods of retrieving meaningful data from these other types of controls.

Further reading

The Document Object Model is covered quite comprehensively by Quirksmode.

Exercise!

Now open the forms exercise page and work through it. The form objects and the ways you can extract data from them are covered on W3Schools.

You may also use the JavaScript scratch pad to try out code quickly.