Simple Javascript and Forms
Forms are used on the web to collect information from the user. This can be anything from a Google search box through to an online application for a financial product. They take hyperlinks to a higher level, by allowing different things to happen depending on what information the form captures. A simple example is Google - entering two different keywords into the search textfield produces two different lists of returned results.
Forms work without Javascript. The HTML specification documents the expected behaviour of a form. Basically, when a form is submitted, all the data within all the named form elements are sent to the URL specified in the form action
. This URL is a server-side script that processes the data, and typically returns a new page in reply.
The simplest fully-functional form would consist of one field:
<form action="http://www.google.com/search"> <label for="q">Search:</label> <input type="text" name="q" id="q"> </form>
This allows a visitor to enter a search term, and when they press Enter it submits the data to Google's search, which in turn returns the first page of results for that search term.
Because this form only contains one field, pressing Enter or Return will submit that form. However if you have more than one field, then a submit button is needed.
The progression of a form is as follows:
- Visitor types in a keyword into the text field
- Visitor presses Enter or Return
- The visitor's browser collects the form data and sends it to the URL
- The server processes the data
- The server sends back a page in reply.
Improving the usability
One problem with the above form is that a person pressing enter immediately submits the form with no data. This isn't a problem for the server really, but doing a query using no keywords isn't likely to be what the visitor intended. The usability of the form suffers because the form submission is triggered, and the browser has to go all the way to the server which in turn returns either no results or the same form again. This round-trip to the server takes some time, and that time could be better spent.
One way to cut down on the unnecessary trip to the server is to validate the form contents before allowing the form submission to continue. If there's a quick and easy way of determining if the data is invalid, then doing this test in the browser before sending the data off to the server improves the usability and responsiveness of our form. In our example, entering no data is clearly invalid data, so lets check that something is entered in the field.
Validating the form
The HTML specification allows a developer to hook in a Javascript validation routine using an event handler. The event handler is called onsubmit
and it is an attribute on the form
tag. The onsubmit
handler can do one of two things:
- Allow the current form submission to continue
- Stop the form submission in its tracks
Javascript validation
The onsubmit
event handler announces its decision by the value the code returns. If a return value of true
is received, then the current form submission is allowed to continue. If the return value is false
, then the current form submission is stopped in its tracks.
<form action="http://www.google.com/search" onsubmit="return true;"> <label for="q">Search:</label> <input type="text" name="q" id="q"> </form>
The above piece of markup is functionally equivalent to our first example. The onsubmit
event handler does a simple return true
, and the form continues being submitted.
<form action="http://www.google.com/search" onsubmit="return false;"> <label for="q">Search:</label> <input type="text" name="q" id="q"> </form>
This piece of markup, in a browser with Javascript enabled, stops the form from being submitted.
Now neither of the above two pieces of markup are functionally useful. They serve only to demonstrate what happens to the normal form submission process when an onsubmit
handler is used. There is a grey area where no return value is specified. Sometimes the form continues to be submitted, sometimes not. Its depends on the browser being used. So its advisable to avoid the hole by specifying an unambigious return value.
Calling a Javascript validation function
Instead of returning a constant true
or false
, we can instead call a function to figure out which return value to issue. This function can then be used to validate the form data, and decide whether to let the form submission continue, or to stop it in its tracks.
<form action="http://www.google.com/search" onsubmit="return validate(this);"> <label for="q">Search:</label> <input type="text" name="q" id="q"> </form>
Here I am calling a function - which we will write - called validate
. This function takes one parameter - a reference to the form. I prefer to use the Javascript keyword this
.
Anatomy of a Javascript validation function
Onto the validation function. We need to do the following:
- Get a reference to the text field
- Check that it isn't empty
- If it is empty, stop the form submission
- otherwise let the form submission continue
In an external Javascript file, called validate.js
:
function validate(f) { if(f.q.value=="") { return false; } return true; }
The parameter f
is a reference to the current form (we passed in the Javascript reference this
). Each field in a form can be referenced by f.fieldName
. In our case, our field is called q
. So f.q
is a reference to our text field. Next we need to get a reference to the value of the text field, so we reference f.q.value.
By comparing f.q.value
with an empty string we can test whether the text field is empty. If the field is indeed empty, then we want to stop the form submission. This is done by the statement return false
.
At no stage do we need to submit the form using Javascript. The only thing the validation routine needs to do is decide whether to continue with the current form submission, or stop it in its tracks.
The form submission process
The process of submitting the form when an onsubmit
event handler is present is:
- Visitor types in a keyword into the text field
- Visitor presses Enter or Return
- The Javascript in the onsubmit handler is run, and its return value is noted
- If the return value is true:
- The visitor's browser collects the form data and sends it to the URL
- The server processes the data
- The server sends back a page in reply.
- If the return value is false:
- Stop the form submission and stay on the current page
- If the return value is true: