JavaScript: Forms and Functions


JavaScript extends the functionality of HTML forms. It allows script writers to write code that can check user input and display additional information to the user. There are two parts to how JavaScript does this. First, JavaScript permits the declaration of named functions much like in C/C++/Java. These functions, designed to perform a specific task such as checking user input for errors, are called when certain events occur. These events may be the user pressing a submit button in an HTML form or merely placing the cursor over a hypertext link. Second, special HTML tag attributes called event handlers can be placed in HTML tags. When an event occurs that the attribute is designed to handle, a short script in the handler is executed. Usually, event handlers contain one or two statements that just call a function or two. To make this work you must both define the function to correctly get information from the form and place the call to the function in an event handler in an HTML form.

Simple Form Without JavaScript

The following is the code for a simple HTML form. It contains a single text field, a submit button, and a reset button. Some notes on forms are also available. In this form no matter what text is entered into the text field, it is sent on to the server when the submit button is pressed. This is a waste of server-side resources.

<HTML>
<HEAD>
<TITLE>Simple Student Number Form</TITLE>
</HEAD>
<BODY>

<FORM ACTION="http://www.ryerson.ca/cgi-bin/mirror/mirror.cgi">
<H3>A Simple Form</H3>
<P>Enter your Ryerson Student Number:
<INPUT TYPE="TEXT" VALUE="123456789"><BR>
<INPUT TYPE="SUBMIT">
<INPUT TYPE="RESET"></P>
</FORM>
</BODY>
</HTML>

Try entering some text that is clearly not a student number and then press the submit button.


A Simple Form

Enter your Ryerson Student Number:


 

A Simple Form With JavaScript

The following code has two additions (a function and an event handler) that make it possible to check what the user enters into the student number text field. In the <form> tag an event handler has been added. The handler calls a function (normally in the head of the document) when the user submits the form. This function checks what was entered into the field. If the user enters a 9 character string, containing only the numbers 0 through 9, the form is submitted. If they did not, the form is not submitted. Try it. Of course this doesn't work if JavaScript has been turned off. For completeness the entire HTML source is shown. The important changes from the simple HTML above are in bold.

<HTML>
<HEAD>
<TITLE>Simple Student Number Form</TITLE>
<SCRIPT Language="JavaScript">
<!--

function checkStdNumber(stdNumber){
   var i
   var chr
   var errorMsg = "Please enter your nine digit Ryerson student number."

   if (stdNumber.length != 9){
      alert(errorMsg)
      return false
   }

   for (i=0; i < stdNumber.length; i++){
      chr = stdNumber.charAt(i)
      if (chr > "9" || chr < "0"){
         alert(errorMsg)
         return false
      }
   }

   return true
}

//-->
</SCRIPT>
</HEAD>
<BODY>

<FORM ACTION="http://www.ryerson.ca/cgi-bin/mirror/mirror.cgi"
      NAME="simpleForm"
      onSubmit="return checkStdNumber(this.sNumber.value)">
<H3>A Simple Form</H3>
<P>Enter your Ryerson Student Number:
<INPUT TYPE="TEXT" VALUE="123456789" NAME="sNumber"><BR>
<INPUT TYPE="SUBMIT">
<INPUT TYPE="RESET"></P>
</FORM>
</BODY>
</HTML>

Try entering a string that is not made of nine numbers, press the submit button, and see what happens:

A Simple Form

Enter your Ryerson Student Number:


Detailed Explanation

The following is a detailed explanation of how each part of the HTML and JavaScript in this page work together to check the student number text field for errors. The logic of how the function evaluates the string is not described here.

The checkStdNumber() function

The function named checkStdNumber() is passed a text string in the variable named stdNumber. If the string is nine characters long and contains only the text characters 0 through 9 the function returns the value true otherwise it returns the value false. There is nothing unusual in the function itself - it is like any other JavaScript function. For example - although it would not be useful - it could be called this way:

result = checkStdNumber("Hi")

in which case the variable result would hold the value false because "Hi" will be copied into the stdNumber variable in the function's parameter list. Since it only has two characters the function will return false. The value the function returns will take the place of the function in the statement - the function is evaluated and returns a value - and in this case false will be returned and assigned to the variable named result.

Of course the script and HTML together do more than this. When the user presses the submit button the function is called with the value the user entered in the text field as a parameter. If the function returns true the form is submitted but if the function returns false the form is not submitted. When someone presses the submit button an "event" that the browser recognizes occurs. It is possible to have the browser invoke code designed to respond to the event. The mechanisms used to tie an event to code to be executed when it occurs are called event handlers. One way to create an event handler is to use a special HTML attributes designed just for this purpose. In this case an event handler attribute of the form tag named onSubmit can be used. onSubmit is defined as part of HTML 4 for this purpose. Here is the onSubmit attribute from the example again:

onSubmit="return checkStdNumber(this.sNumber.value)"

Here is a description of each part of the event handler. Each bolded part is discussed separately:

onSubmit="return checkStdNumber(this.sNumber.value)"

The format for an event handling attribute is the same as the format for any HTML tag attribute. The attribute name is followed by an equals sign and then a value in quotes. In this case what is inside the quotes are JavaScript statements to be executed when the event occurs. Several events are defined for certain form tags. onSubmit is defined for the form tag itself. The JavaScript statements in quotes are executed when the form is submitted.

onSubmit="return checkStdNumber(this.sNumber.value)"

checkStdNumber() is a function call. In order to pass the value returned by the checkStdNumber() function back to the event handler, the return keyword is added. If you omit this, the form will be submitted regardless of what the function returns.

onSubmit="return checkStdNumber(this.sNumber.value)"

Inside the event handler this.sNumber.value is passed into the checkStdNumber() function. The dot notation indicates that sNumber is a property of the this object and that value is a property of the sNumber object. But what is this? Each form tag in an HTML document is represented by a JavaScript object that allows script writers to examine properties of the form object. this is a special keyword that is used to refer to the JavaScript object that represents the tag an attribute is within. Since this appears inside an attribute of the form tag it represents the form tag. Since the text field is an input tag named sNumber inside the form tag it can be accessed by this.sNumber, and since each input field has a property named value that holds the current string in the text field it can be retrieved with this.sNumber.value.

In other words,

Therefore this.sNumber.value will retrieve the value in the text field.