EIW Fall 2000 Lecture Notes - JavaScript & Form Field Validation


Embedded Scripts

HTML includes a <SCRIPT> tag that along with the end tag </SCRIPT> surround a section of a document that contains instructions to the browser written in a scripting language. There are a number of scripting languages that are currently supported by browsers, JavaScript and VBScript are the most popular. We will explore JavaScript, Visual Basic programmers might want to look up the specifics of VBScript on the WWW (VBScript is supported by I.E.).

When a JavaScript-enabled browser receives a document that contains JavaScript commands (inside SCRIPT sections) the browser interprets (executes) the script commands as the document is loading. In addition, there are many user actions that can trigger sections of JavaScript, for example clicking on a button or moving the mouse over an image can be set up to trigger a JavaScript script.

JavaScript commands can be used for a variety of purposes, here are some examples:

We will look at a number of uses for JavaScript eventually, but for now we will focus on a few examples and move on to using JavaScript to make sure that users fill out forms properly (this task is called form validation).

Some JavaScript Basics

JavaScript is not the same as Java (the Java programming language), although it is similar in syntax. I've seen it stated that JavaScript is a subset of Java, although I'm not completely sure this is true. I do know that it is very similar and that Java programmers can do JavaScript without much of a learning curve.

JavaScript commands are embedded inside SCRIPT sections of an HTML document. Typically the JavaScript is placed inside HTML comments as well, to prevent browsers that don't understand the SCRIPT tag from thinking the JavaScript commands are part of the HTML. The SCRIPT tag has an attribute named LANGUAGE that should be set to the value "JavaScript" (this is the defaul. Here is the general idea:

<HEAD>
<TITLE>Foo the wonderful Foo</TITLE>
</HEAD>
<BODY>

blah, blah, blah ...

<SCRIPT LANGUAGE=JavaScript>
<!-- 
   this is where the javascript goes
// -->
<SCRIPT>
</BODY>

The SCRIPT tag can actually be anywhere in the document, very often it appears in the HEAD. There can be multiple SCRIPT sections as well (this is quite common).

NOTE: The end of the comment in the above HTML starts with a JavaScript comment // (JavaScript comments are like C++ comments).

Objects and JavaScript

JavaScript is an object oriented languages, it supports the idea of a object that can have associated methods and data members. One important JavaScript object has the name document and we can use this object in JavaScript programs to extract information about the current HTML document as well as to add content to, or make changes to the document. The document object has a method named write that allows us to add new content to the document - here is a simple example:

<H1>This document includes some JavaScript</H1>
<HR>
 <SCRIPT LANGUAGE="JavaScript">
 <!--
   document.write("Hi Dave");
 // -->
 </SCRIPT>

 <HR>
 <H4>This is below the JavaScript stuff</H4>

This document includes some JavaScript



This is below the JavaScript stuff

The example above is silly, it would be easier to just put the "Hi Dave" in the document directly - but the idea is that JavaScript can be used to add content that might not be available ahead of time. For example, we can use the document object to access information about the current document and include this information in the document itself. Here is an example, notice the use of the JavaScript string concatenation operator +.

<H1>This document includes some JavaScript</H1>

<HR>

<SCRIPT LANGUAGE="JavaScript">

<!--

  document.write
    ("Some info about this document:<BR>" +
    "Title: " + document.title + "<BR>" +
    "URL: " + document.location + "<BR>");

  document.write
    ("Some info about the browser you are using:<BR>" +
    "Name: " + navigator.appName + "<BR>" +
    "Version: " + navigator.appVersion + "<BR>");

// -->
</SCRIPT>

<HR>

<H4>This is below the JavaScript stuff</H4>

This document includes some JavaScript



This is below the JavaScript stuff

There are other objects and object types available when using JavaScript, here is another example that uses the Date object class to display the current time (just to give you an idea of the kind of stuff you can do). In this script we create a variable named d that is of type Date, then extract the time and date using some of the methods defined for objects of type Date. (Don't worry if this is a bit confusing so far, we are just looking at the kind of stuff you can do with JavaScript - we will talk about some JavaScript objects more formally later).

<HR>
<SCRIPT LANGUAGE="JavaScript">
<!--
  // create a date object 
  // with the current time and date
  var d = new Date(); 

  document.write(
           "<H2>It is now:" +
           d.getHours() + ":" +
           d.getMinutes() + ":" +
           d.getSeconds() +
           ", " + (d.getMonth()+1) + "/" +
           d.getDate() + "/" + d.getYear() + 
          "</H2><BR>" );
// -->
</SCRIPT>
<HR>



Handling events

JavaScript can respond to events caused by user actions while viewing the HTML document - for example by clicking on an object. Many HTML tags support attributes that are bound to JavaScript, for example the attribute onClick can be specified in the INPUT tag when defining a button. When the user clicks on the button, the value of the onClick attribute is executed as a JavaScript command. Try clicking on the button in the following example:

<HR>
<FORM>
  <INPUT TYPE=BUTTON 
         value="Please Don't Click Me"
         onClick='alert("I asked you not to do that!");'>
</FORM>
<HR>



JavaScript provides an alert object you can use to alert the user of a problem.

You can add event handlers to many HTML tags, although the only kind of tags that will react to clicks are links, buttons and a few other form elements. Typically the code to handle events is supplied in a common SCRIPT section placed in the document head - and the individual events simply call subroutines defined in this common section.

There are a variety of different kinds of events that can be handled using JavaScript - the onClick event is just one. Another event is called onFocus and happens when a button receives the input "focus", this happens when the mouse is used to select the button, or when the user presses tab until the button is highlighted.


Subroutines

JavaScript Subroutines are called "functions", and they look similar to C functions in syntax. JavaScript is like perl in that variables don't have explicit data types - you can use a variable to hold any kind of data at any time. Javascript function parameters must be declared in the function definition, although you just need to supply a list of the parameter names. Here is an example function definition for a subroutine that adds two numbers:

<SCRIPT>
<!--
function add (x,y) {
  return(x+y);
}
// -->
</SCRIPT>

Here is another example - some JavaScript functions that can be used to build an HTML table. The functions operate on string variables, and return string values as well.


<SCRIPT LANGUAGE=JavaScript>
  function maketable(rows) {
     return("<TABLE BORDER=1>" + rows + "</TABLE>");
  }

  function makerow(cells) {
     return("<TR>" + cells + "</TR>");
  }

  function makecell(x) {
      return("<TD>" + x + "</TD>");
  }
</SCRIPT>

<H2>Here is some information about this document:</H2><BR>

<SCRIPT>
  document.write(
     maketable(
       makerow( makecell("Title:") + makecell(document.title)) +
       makerow( makecell("URL:") + makecell(document.location))  
     )
  );
</SCRIPT>

Here is some information about this document:


JavaScript Operators and Control Structures

JavaScript includes a typical set of operators and control structures, the syntax is nearly identical to C or C++. The only major difference is that variables are declared without any type, instead you use var statement to declare a variable. Here are some examples just to convince you that you already know this most of this stuff:

<SCRIPT>
  // for loop that prints hi dave 10 times
  var i;

  for (i=0;i<10;i++)
    document.write("Hi Dave<BR>");

  // a function that counts out loud
  function count_out_loud( max ) {
    var i=1;

    while (i <= max ) {
       document.write("<H4> i is " + i + "<BR>");
       i++;
     }
  }

  // now call the function
  count_out_loud(6);

  // a function that returns the maximum of 2 numbers
  function max(a,b) {
   if (a > b) 
     return(a);
   else
     return(b);
  }

  // test out the function
  document.write("The maximum of 17 and 24 is " + max(17,24) );

  </SCRIPT>


Using JavaScript to Validate Forms

One important use for JavaScript is to make sure that users fill in a form with valid values before submitting the request to a CGI program. We can include JavaScript that checks the fields of a form for valid values and won't allow the submit button to work until all fields have valid values.

NOTE: Although we can use JavaScript to make sure that anyone using our form can only submit valid requests - remember that anyone can create a request by hand - so our CGI programs still need to check for errors in each submission (errors like not filling out each field).

Assuming you have an HTML form and you want to use JavaScript to validate form fields, you need to do the following:

<FORM METHOD=GET ACTION=foo.cgi onSubmit="return(checkfields())">

The function checkfields must be defined somewhere in the document (inside a SCRIPT section). The return(checkfields()) looks awkward but is necessary - we need to explicitly use the return statement around the call to checkfields to prevent the submission from actually happening.

Within the checkfields function you will need to determine whether the current value of each form field is valid. In some situations you might want to make sure the user typed in anything, in other cases you might actually want to make sure, for example, the entry is a valid integer or is in a valid range of values.

Accessing Form Fields

The entire HTML document is available from JavaScript via the document object (the same object we've been using to add content). Each document can hold a number of forms, so we need to know which form we are trying to access. For our example we will assume that there is only one form.

The document object member forms is a JavaScript array of all the forms in the document - to get the first form in the document you can do this:

var myform = document.forms[0];

The variable myform is now our form. Within a form can be a number of elements (input fields, radio buttons, submit buttons, etc.). We can also access the elements of the form using the JavaScript array syntax used above to access the first form in the document, so we could do something like this to get the first field:

var myfield = myform.elements[0];

It's probably a hassle to keep track of which field comes first in the form, so we can also gain access to form elements by using the name of the field. Suppose there is a form field defined as follows:

<INPUT TYPE=TEXT NAME=foo>

We can also access this field with the following statement:

var thefield = myform.elements["foo"];

Where myform is the form and foo is the name of the field. JavaScript automatically makes this associative array available.

To get the actual value the user typed in to a field, you must use the value member of the field object. So you could check to make sure the the field myfield was not empty with the following:

if (myfield.value == "")
   // error - nothing was entered

This sounds complicated (and it is), but there is a much easier way to get access to form fields. To use this method you must give the form a name (put a NAME= attribute inside the FORM tag) and each field must have a name. Here is a sample form with names included in all the important tags:

<FORM METHOD=GET ACTION=foo.cgi NAME=DavesForm>

 Color: <INPUT TYPE=TEXT NAME=ColorField><BR>

 Size:  <INPUT TYPE=TEXT NAME=SizeField><BR>

<INPUT TYPE=SUBMIT>

</FORM>

Color:
Size:

Once we have the above form defined, any JavaScript inside the same document as this form can access the value of the color input field with the following:

document.DavesForm.ColorField.value

and the value the user entered in the size field as:

document.DavesForm.SizeField.value

This object naming hierarchy is know as the "Document Object Model" and is quite extensive - there are names like this for all the elements inside any HTML document (some names can get quite large!).

Finally - we tie all this together in a single document. We need the form with the onSubmit attribute set to call the checkform function and the JavaScript definition of the checkform function.

<SCRIPT>
  // here is the JavaScript code
  function checkform() {
    if ( document.DavesForm1.ColorField.value == "") {
       alert("You need to specify a color");
       return(false);
     }

    if (document.DavesForm1.SizeField.value == "") {
       alert("You need to specify a size");
       return(false);
     } 

    return(true);
  }

</SCRIPT>

<H3>Here is a form for you to fill out</H3>

You must enter a value in each field, then press submit.<P>

<FORM METHOD=GET 
      ACTION=foo.cgi 
      NAME=DavesForm1 
      onSubmit="return(checkform())">

Color: <INPUT TYPE=TEXT NAME=ColorField><BR>

Size:  <INPUT TYPE=TEXT NAME=SizeField><BR>

<INPUT TYPE=SUBMIT>

</FORM>

Here is a form for you to fill out

You must enter a value in each field, then press submit.

Color:
Size: