WebDevelopersJournal.comTips on Web Page Design, HTML and Graphics
SITE SEARCH
Newsletters
HTML (M-F) Text (M,TH)



Jobs at webdeveloper.com

Resources By Subject
Technical
Graphical
Authoring
Business
WDJ resources
Archive

internet.com

internet.commerce
  • Partner With Us
















Developer Channel


Find a web host with:
CGI Access DB Support Telnet Access
NT Servers UNIX Servers



Semi-automatic?

JavaScript
JavaScript Helper:
Meet Paige Turner, the least geeky geek we've ever come across.

Variables and Operators Explained:
First of a three part guide to JavaScript basics.

Controlling Forms:
Enhance your HTML forms with a touch of JS.

DHTML:
Forget how it works, let's see some in action!


Using JavaScript To Control Forms - Part 2

Closer control over form inputs


by Jon Perry

The second part of our series on using JavaScript to improve the quality of forms looks at one final aspect of 'required' fields, the Select element. It also covers Regular Expressions that can be used to limit the kind of characters accepted in a field, and techniques using Hidden fields that can make received data easier to understand.
February 3, 2000

This is Javascript for IE5. See our policy on browser-specific JavaScript.

In the first article in this series, we examined several techniques to prevent forms being submitted with incomplete data. This article begins by covering the final element of the 'required' technique, which is the <SELECT> element.

We will then examine the Regular Expression, and use it to narrow and refine the range of inputs allowed in a form field. Finally, we shall look at techniques which use the HIDDEN field to pre-process form data into a more useable style.

The result of learning all this JavaScript is that we are able to create forms that validate and process their data before they are sent - saving the recipient work.

Required SELECT Field

The <SELECT> element offers the viewer several display options. We can create either a drop-down list or scrollable list box.

The basic selection process is either exactly the same as a group of radio boxes, or similar to a group of checkboxes, with the exception that the viewer must choose at least one of the available options.

The <SELECT> element suffers from the same problem as radio boxes. It is possible for the viewer not to select an item at all, and we wish to avoid this. And again like radio boxes, it is possible for the viewer to accidentally or lazily submit the default option.

This is not a problem, technically, but it will result in unbalanced results from the form. You will find an unreasonable bias towards the default option, rendering any information gained from the form useless.

The following code prevents the user from submitting the default option from a SELECT element. The default option must be a dummy option, which says something like 'Please choose'.

<HTML>
<HEAD>
<TITLE>Required Select Field</TITLE>
<SCRIPT>
function validate() {
if (mainform.Salary.options[0].selected) {
alert('Please choose a Salary Range.');
event.returnValue=false;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="mainform" ACTION="http://hoohoo.ncsa.uiuc.edu/cgi-bin/post-query" METHOD="POST" onsubmit="validate();">
<SELECT NAME="Salary">
<OPTION VALUE="0" SELECTED>Salary Range</OPTION>
<OPTION VALUE="1">Less Than $10,000</OPTION>
<OPTION VALUE="2">$10,000-$20,000</OPTION>
<OPTION VALUE="3">$20,000-$30,000</OPTION>
<OPTION VALUE="4">More than $30,000</OPTION>
</SELECT>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>

We intercept the onsubmit event, and get re-routed to the validate() function, which checks the form for illegal input.

if (mainform.Salary.options[0].selected) {

This line asks if the first option is the selected option. The first option in this program is the dummy and default option.

Note that we use 0 instead of 1 for the first option. Lists and arrays are often zero-based, which means the first item is at index 0.

If the code is true, i.e. mainform.Salary.options[0] is selected , then the viewer has not satisfactorily answered the question, and is prompted to try again. We must also cancel the onsubmit event, in order to prevent the incorrect form being submitted.

This technique also works for SELECT elements with the MULTIPLE attribute, and for different SIZE attributes. The code will prevent any submission containing the dummy element, but otherwise will accept the input.

The next validation technique involves checking the actual text input to a field, and uses Regular Expressions.

Using Regular Expressions

Regular Expressions define templates for strings and numbers. A template is a pattern of characters. Regular expressions provide a complete syntax for defining any template - so we can detect patterns like two letters and a number, a word with the letter 'w', a word without an 'e', and so on.

The following program scans any input for exactly three consecutive lower case letters. Depending on the result of the scan, the viewer is told whether they did or did not input exactly three consecutive lower case letters.

<HTML>
<HEAD>
<TITLE>Regular Expression</TITLE>
<SCRIPT>
three=/^[a-z]{3}$/;
function validate() {
if (three.test(mainform.TEXT1.value)) tlc='';
else tlc=' not';
alert(mainform.TEXT1.value + 'is'+tlc+' exactly three consecutive lower case letters.');
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="mainform" onsubmit="validate();">
<INPUT TYPE="TEXT" NAME="TEXT1">
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>

The variable three in this program is a regular expression.

We may also use the JavaScript object RegExp to define the variable.

three=new RegExp("^[a-z]{3}$");

The regular expression three is a template for exactly three consecutive occurrences of any character from a through to z. The ^ and $ sign match for the beginning of the text and the end of the text respectively. This ensures that the template defines a pattern that has exactly three lower case letters between the start and end of the text.

When we come to use the regular expression variable, we use it in a test against a string.

The general syntax for the test method of the regexp object is:

regexp.test(string)

In this case, we use:

three.test(mainform.TEXT1.value)

This line tests the text entered in the text box against the regular expression, and returns true if it finds the pattern in the text.

We can define a regular expression to look for any character and any pattern. Typical uses for regular expressions include a name, which may only contain letters, plus hyphens and full stops, or a phone number, which may only contain numbers. Or, if you have an indexed database, you may only allow entry of reference numbers, e.g. A756 or D342.

<HTML>
<HEAD>
<TITLE>Database</TITLE>
<SCRIPT>
refno=/^[A-Z]{1}\d{3}$/;
function validate() {
if (refno.test(mainform.REFER1.value)) alert('Article '+mainform.REFER1.value+' has been emailed to you.');
else {
alert('Invalid Reference Number. Please try again.');
event.returnValue=false;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="mainform" onsubmit="validate();">
<INPUT TYPE="TEXT" NAME="REFER1">Enter reference Number (e.g. F647)
<BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>

The RegExp in this program looks for a string containing an upper case letter and exactly three digits following it.

Regular Expressions

Basic regular expressions can be defined using the following:

Character What it represents
\n Newline
\t Tab
\(character) A literal (character), e.g. \* represents *
\xnn ASCII character nn (hex)

These may be grouped, so

[abc] is an a, b or c
[abc\(] is an a, b or c or (.
[a-zA-Z] is any lower or upper case letter.

We can also use negation.

[^abc] is any character except for a, b or c.

Special groups include:

\w [a-zA-Z0-9]
\W [^a-zA-Z0-9] or [^\w]
\d [0-9]
\D [^0-9] or [^\D]

We can also define the number of occurrences:

{n,m} Match between n and m times
{n,} Match at least n times
{n} Match exactly n times

We can also match for text position:

^ Match with start of text
$ Match with end of text

So,

refno=/^[A-Z]{1}\d{3}$/;

defines a regular expression which looks for exactly one of [A-Z] followed by exactly three of [0-9].

Common regular expressions include:

/[a-zA-Z]{1,}/ At least one and only letters
/\d{1,}/ At least one and only numbers

 

HIDDEN INPUT type

The HIDDEN INPUT type is invisible to the viewer, but can be submitted along with the form data. This is useful because we can use client-side JavaScript to pre-process the form.

Let us look at an example.

<HTML>
<HEAD>
<TITLE>HIDDEN</TITLE>
<SCRIPT>
function preprocess () {
message='';
if (mainform.MUSIC.checked) message+=' Music,';
if (mainform.SPORT.checked) message+=' Sport,';
if (mainform.TRAVEL.checked) message+=' Travel,';
if (message!='') message=message.substr(0,message.length-1)+'.';
if (message=='') message+=' Nothing.';
mainform.DETAILS.value=mainform.FIRSTNAME.value+' '+mainform.LASTNAME.value+' likes'+message;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="mainform" ACTION="http://hoohoo.ncsa.uiuc.edu/cgi-bin/post-query" METHOD="POST" onsubmit="preprocess();">
<INPUT TYPE="TEXT" NAME="FIRSTNAME">First Name
<INPUT TYPE="TEXT" NAME="LASTNAME">Last Name
<BR>
<INPUT TYPE="CHECKBOX" NAME="MUSIC">Music
<INPUT TYPE="CHECKBOX" NAME="SPORT">Sport
<INPUT TYPE="CHECKBOX" NAME="TRAVEL">Travel
<INPUT TYPE="HIDDEN" NAME="DETAILS">
<BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>

With this code, once the form has been submitted, we intercept the onsubmit event, and pass control to the preprocess() function.

The preprocess() function examines the data from the form, and constructs a value for the HIDDEN INPUT type field. This presents a message to the recipient of the form data like:

Jon Perry likes Music, Sport, Travel.

HIDDEN techniques for the SELECT element

We can apply the same theory to the first example in this article to parse the value of the salary selection group. The code is basically the same as before, with a few additions.

<HTML>
<HEAD>
<TITLE>Required Select Field</TITLE>
<SCRIPT>
salarytext=new Array('Less Than $10,000','Between $10,000 and $20,000', 'Between $20,000 and $30,000','More than $30,000');

function validate() {
if (mainform.Salary.options[0].selected) {
alert('Please choose a Salary Range.');
event.returnValue=false;
}
else preprocess();
}

function preprocess() {
mainform.hiddensalary.value='Salary : '+salarytext[mainform.Salary.value-1];
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="mainform" ACTION="http://hoohoo.ncsa.uiuc.edu/cgi-bin/post-query" METHOD="POST" onsubmit="validate();">
<SELECT NAME="Salary">
<OPTION VALUE="0" SELECTED>Salary Range</OPTION>
<OPTION VALUE="1">Less Than $10,000</OPTION>
<OPTION VALUE="2">$10,000-$20,000</OPTION>
<OPTION VALUE="3">$20,000-$30,000</OPTION>
<OPTION VALUE="4">More than $30,000</OPTION>
</SELECT>
<INPUT TYPE="SUBMIT">
<INPUT TYPE="HIDDEN" NAME="hiddensalary">
</FORM>
</BODY>
</HTML>

These changes produce data that can easily read by the human eye, rather than single digit codes that require interpretation.

There are a few more techniques we are going to look at in the last article in this series, such as 'intelligent forms', which change their questions according to certain answers, using JavaScript to make forms look good, and dynamically changing a form's content - useful for quizzes.



Jon Perry is a Freelance Author and Programmer from the UK.
Suits PonytailsPropheadsContact WDJDiscussWeb AudioSearch

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs