<%response.buffer=true%> <% yere = year(date()) Response.Expires = 0 %> JavaScript Intro

Forms & JavaScript

Purpose Of Forms: One of the most important ways to interact with the user are via forms. Forms are an instrinsic part of HTML. Anytime a user types into a "text" box, whether it is to send an email, make an online purchase or login to a web site, it is done so by using a form. Forms routinely consist of "elements" which are the checkboxes, text boxes and submit button that allow the user to enter data, and to submit the data to another web page. The page that handles the data retrieved in this manner is sometimes called the formhandler. The formhandler is identified by the action attribute in the form tag:

<form name="myForm" action="myFormHandler.php" method="post">

Frequently, as in the example above, the formhandler is written with server side code. This is evident here because of the extension of the page identified in the action attribute. It is "php" in this case, but could also be "asp", "aspx", "jsp", "cfm", "pl" and others. Each of these identifies a different server side scripting technology.

The method attribute indicates the way in which the data is sent to the formhandler. The method is usually holds the value of "post" or "get", in which "get" is the default if no method is specified. "get" is more limited in the amount of data that can be sent, requires special character handling and can allow the user to "see" the data submitted via the Query string (the data following the question mark after the page name in the address bar). For most forms, we will select "post", which has none of those limitations. The "get" method of submission however is routinely used to send "loaded" querystrings with parameters in links. For much greater detail on form operation and specific handling and selection of elements please view the following: Forms PowerPoint

Starter Form: Use this blank form to start: starter form
Form Event Handlers: JavaScript can be used to interact with form via event handlers. The most important event handler exists in the form tag itself, and it is called "onsubmit". This formhandler is frequently used to attach form "validating" JavaScript functions to check the data on the form prior to submission:

<form name="myForm" action="myFormHandler.php" method="post" onsubmit="myJSFunction();">

To do this properly, you would could use the "return" keyword inside of the onsubmit formhandler. This return is either true or false, as returned from the function. If the return is "false" the form is not submitted!

<form name="myForm" action="myFormHandler.php" method="post" onsubmit="return myJSFunction();">

Not all events need to be part of the form itself. For example, you can even use the "onload" event in the body tag to select the first textbox on a form for the user. This allows the cursor to "jump" right to that textbox when the page loads:

<body onload="document.myForm.myTextBox.focus();">

This of course could instead be done via the window.onload event, or the addOnLoad() function added in our js template.

Form Validation: One of the primary jobs for which JavaScript is best suited is form validation. Since JavaScript is default client side script, it is the scripting language of choice for handling a user's form. We use client side script to check forms prior to server side processing, primarily to take work away from the server. It makes more sense to "validate" (check for proper data) on the client's computer prior to form submission, rather than sending the bad data back and forth to the server! Once the form is deemed acceptable by the client side JavaScript, the data is sent to the server for processing, which usually means the data is destined for automatic email generation, database processing, or both.

Data validated by JavaScript on the client only is not not advised. The data will still need to be validated on the server side, as we can't even guarantee which page sent the data!

Forms 2012: Using JavaScript with forms is changing rapidly. For many years one of JavaScript's main tasks was to validate data entered on a form before it was submitted to a server side page for processing. However as we move toward HTML5, form validation is being built into the browsers. Therefore, is JS form validation going away?

HTML5 & Form Validation: Validation in HTML5 can be extremely easy to use. View the following form element:

<input type="text" name="FirstName" required="required" />

The required attribute above will use an HTML5 capable's browser to use it's built in ability to validate forms.

Here's a link to some HTML5 Form Validation Resources

JavaScript Form Handling in an HTML5 World: While the HTML5 specification will eliminate many facets of JavaScript form validation, there are cases where what your client asks for will lead you toward a more complicated mechanism for handling form validation. For example, what if the contents of one field change the handling of another? This may not be so easily addressed via HTML5 form validation.

Apprehending Form Elements: Each form, and in turn, each form element on the page can be identified, and addressed (apprehended) using the document object model (DOM) or Browser Object Model (BOM). The form itself, each element inside, and most important, the VALUE as input (or not) by the user is available via the BOM in this manner:


document is a JavaScript keyword, but we substitute the name of the form, and the name of the element in the example above. To read the current value of a textbox named "FirstName" on a form named "myForm" into a variable, we could do this:

var myValue = document.myForm.FirstName.value;

From here, we can check the value to see if the user has entered correct data. The most common use of form validation is merely to determine whether a user has entered ANY data at all, and to return the user to the form element, and request that data be entered, prior to form submission.

While we can apprehend form data in the way above, we find it is difficult to do long forms in this way. Each element would need to be specifically called out by name, and dealt with accordingly. Luckily many of the objects, such as the forms, allow us to access form elements, and the data inside them, as a built-in array. We can use the for loop to access the elements in the array, and process them in turn. Here we get data from a form element via an array:

var myValue = document.forms[0].elements[0].value;

To determine what type of form element we have, we can access the "type" of the element:

var myType = document.forms[0].elements[0].type;

We can also determine what "name" has been given to the specific form element:

var myName = document.forms[0].elements[0].name;

The following example enumerates (displays) the form elements, and the current contents of the form elements (values) when you click on the links at the bottom of the Page: Form Elements

In the above example, the values change based on your input to the form. Note that the "EMPTY" is put there via the code on the page. An unfilled form value returns an empty string.

The type of the element effects the way we need to access the value inside. Radio buttons and check boxes use ".checked" to determine if the value is either "true" or "false". The "name" of a select option is "select-one" (the single option version) and selected option is even more obscure as it is accessed by the "selectedIndex" array of the "options" elements. The select option therefore has yet one more lower array!

Focus & Blur: Many form elements have a focus() method that allows us to place the cursor into a textbox on page load:

<body onload="document.myForm.myTextBox.focus();">

We can also use a related event handler, onfocus, to trigger a function:

<input type="text" onfocus="myFunction();">

The onfocus event handler is therefore in reaction to a focus event! When we click on a form element, it is said to receive focus.

Compare the focus event to the related blur event which is called when focus is released on the element, for example when we click on a second element. Only one element at a time can be the focus.

The related onblur event handler is especially useful because we can use it to check the data just entered in the element.

The Fundamental Form: When we build a form, we need to keep our audience in mind. It is usually a good policy to request only necessary information from a user, who may think twice if asked too many questions on a form. Since we are going with the assumption most of our form fields are REQUIRED to have some sort of user input, our most fundamental form will feature a form array looping structure to check that SOME data has been entered in each text box on a form, and will stop form submission and request further data from the user for each empty form element:

function checkForm(thisForm){ //this was used inside form, can be passed to function
   for(x=0; x<thisForm.length; x++)
      alert("Please enter required field: " + thisForm.elements[x].name); //show user we need input
      thisForm.elements[x].focus(); //focus the cursor in the textbox that was not filled in
      return false; //return a "false" to the form, telling it not to submit
return true; //if passed all checks, submit form

We send the entire form into the function, and can loop through all the elements of the form with the "length" property of the form. Each form element is a new item in the form element array. If any "value" is empty, we show the user an alert box, requesting data be inserted in the specific text box on the form. We access the element and use the "focus()" method to put the cursor into the text box for user convenience.

The "return false" indicates to the form NOT to submit! If all elements pass the test, the code falls to the "return true" statement, which tells the form to go ahead and submit the data. The "onSubmit" event is targeted in the form element in this manner:

<form name="myForm" action="myformhandler.asp" onSubmit="return checkForm(this);">

The keyword "this" can be used while inside the form tag itself to refer to the current form. You may remember the control word "this" also being used to access a current object, which in this case, the form is! Example: Simple Check Form

Checking for Specific Data: While the above example gets us started by seeing a user has entered some data, we often wish to limit the type of data a user may input. The easiest way to do this does not involve checking form data. If we know a user needs to input the State they live in, for example, we may elect to put all the states into a select option, to eliminate the possibility of typographical errors. However, we can't do this for all data, for example, an email address.

Regular Expressions: There is a cross-language means for matching patterns in strings that greatly reduces the amount of string handling we will need to do in validating forms. Regular expressions were first used in relation to searching for complicated string matches in UNIX programming, and now exists in JavaScript, Java, VB, C#, PHP and many other programming languages.

Once we have determined how to "match" a particular string, we can use this to return a true or false on whether the string matches that pattern. The best news of all is that many of the most common regular expression patterns have already been built for us. If we can find the match that best suits our purposes, we can use these free in our programs, or adapt them further for our use. Here is an example of a JS regular expression match for a Social Security Number Check. Here is another for an Email Check.

Checking Other Form Elements: While it is easy to check textboxes and textareas for some type of input by checking the value property, it is different for other types of form elements. Radio buttons and checkboxes usually have a value (what the user chooses by clicking the element) so we need to see if the user has "checked" that item with JavaScript.

Grouping Radio Buttons & Checkboxes: For radio buttons (or checkboxes) to operate together, each button to be included must have the same name:

Red: <input type="radio" name="FavoriteColor" value="red" /><br />
Blue: <input type="radio" name="FavoriteColor" value="blue" /><br />

Yellow: <input type="radio" name="FavoriteColor" value="yellow" /><br />

Once a set of radio buttons each have the same name, each button is an element of an array that can be called by the group's name attribute. We can determine which radio button of a group is currently checked by looping through the button array:

for (var x=0; x<document.myForm.FavoriteColor.length; x++){
    if (document.myForm.FavoriteColor[x].checked){
        alert("Aha! You are a " + document.myForm.FavoriteColor[x].value);

An easy way to validate a radio button group is to check to see if any value is assigned to a variable while looping through the values. If no value is assigned to the variable after a complete loop, (it would contain null) then no item was checked:

for (var x=0; x<document.myForm.FavoriteColor.length; x++){
    if (document.myForm.FavoriteColor[x].checked){
    var myTest = document.myForm.FavoriteColor[x].value;       
    alert("Your favorite color is " + document.myForm.FavoriteColor[x].value);

if(myTest == null){
    alert("You didn't select a color!");

For form validation purposes, we can deal with checkboxes in the same manner as radio buttons. Here is an example form that demonstrates the code above: Which Color

Checking All Checkboxes: With checkboxes we can allow a user to select multiple items. Sometimes we want to allow users to check or uncheck all checkboxes on a form at once. This is common if you are going to delete multiple items, or send emails to users, etc.

To do this, you can choose one checkbox to be the toggle. As the "toggle" the state of that checkbox, when checked or unchecked, will cascade to all applicable checkboxes on the form:

function toggle(myCheck){
    for(var x=0; x<myCheck.length; x++){
    myCheck[x].checked = document.myForm.checkAll.checked;

The "toggle" function is called everytime the checkbox named "checkAll" is checked. The onChange event of the checkbox is used to trigger the function:

Check/Uncheck all:<input type="checkbox" name="checkAll" onclick="toggle(document.myForm.myEmail);">

Here is an example: Toggle Email

Select Options: Select option form elements are handled in a different manner. The individual options inside a select are accessed as an array, in a similar manner to a radio button. We can loop through the select array to see which item is currently selected. Here is a JavaScript snippet that loops through a select object that contains various states:

for (var x=0; x<document.myForm.myState.length; x++){
  if (document.myForm.myState.options[x].selected){
    var myTest = document.myForm.myState.options[x].value;
    alert("Aha! You're from " + myTest);

To check to see if at least one item is selected, however, it is not as easy as with a radio button. Since a select option normally has the first item in the array "selected" by default (if no other option is chosen) we must avoid the first item in the array. Note this example select object:

<select name="myState">
<option value="CA">California</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>

In the above example, California is the first item in the select array (with an index of zero). Since it is the first element in the array (the first option) it will automatically show as selected, unless we specify otherwise! It is the nature of the select to have at least one item selected! Since we routinely want the user to make their own selection, we'll amend the select object:

<select name="myState">
<option value="">Select A State</option>
<option value="CA">California</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>

Now we have a "label" inserted into the zero array element (first element) of the select object! This is to instruct the user to choose a different option, and to give us a "default" that indicates no option has yet been selected! Now to see that a user has entered some choice in the select element, we can simply test for the first element in the array. Any OTHER choice would be acceptable:

if(document.myForm.myState.options[0].selected == true){alert("Please select a state!");}

To work with the value of the selected option, we can use the "selectedIndex" property. This gives us the first selected option in a select object. We can get the currently selected value out of the select option with one long line of code:

var myState = document.myForm.myState.options[document.myForm.myState.options.selectedIndex].value;

If we pass the "myState" select object into the function, we can shorten this code considerably:

function checkState(myState){
    var myState = myState.options[myState.options.selectedIndex].value;
    alert("Your state is " + myState);

Here is an example that demonstrates the select object: Which State

Checking Multiple Element Types: On our basic forms page we checked text boxes for data entry. We later showed how checkboxes, radio buttons and select options need a different strategy. View the following example for how to check for required form data by adding a single letter to the name of the element: checkReq

Validating Complex Forms: When we work with forms we benefit from starting with a form that has some validation already present in it.  The third version of the JS template adds form validation functions such as empty() which checks a set of radio buttons, checkboxes, a select or text type form elements for required selection. It requires some sort of data entry (any string data, any type) of input elements (text,password) or textarea elements: js_template3.htm

Get the code here: JS Template Version 3 Zip File

Miscellaneous Form Tricks

Processing User Input: The following example attempts to "normalize" (format) inconsistently "cased" data as entered by a user. There are 3 custom functions on this page. The most critical of them is called "capFirst", which is designed to take any string of data, and capitalize the first letter of each word, set to lower case the rest of the word and rebuild the string, and return the string out of the function: capFirst

The Select Object As Navigation: The select object is also used to navigate between web pages. We can access the "onChange" event handler to load a new web page when a the user selects an option. Here is a small form that includes one select object:

<form name="myNav">
<select name="myList" onChange="jumpTo(myList)">
<option value="#">Click N Go!</option>
<option value="http://www.google.com">Go To Google</option>
<option value="http://www.yahoo.com">Go To Yahoo</option>

There is no submit button on this form, because there is a function named "jumpTo" which is called when the option selected is changed. The entire select object, named "myList" is sent to a function:

function jumpTo(list){
  var myLink = list.options[list.selectedIndex].value;
  if(list.selectedIndex != 0){
    location.href= myLink;

Once the select object (now named "list") is sent to the function, the selected value is determined, and if the index is not zero, the location object is used to change the web address! (Send the user to a different page).

Remember that the "zero" index in this case would be the label "Click N Go!". Since this is the default, we don't want to use this for navigation, as the user would need to CHANGE the current selection (using the onChange event)! Click N Go

Submit Only Once: Sometimes users get impatient and click the "submit" button on a form about a dozen times, wreaking havoc on the database. We can stop the user from doing this by substituting a "button" type form element for the "submit" button, and then disabling the button after one click:

<input type="button" value="Submit, only once!" onclick="this.disabled.true; this.form.submit()" />

A better version would use a custom function that would check for valid data, and then submit the form.

Limit Textarea Characters: Textareas do not have the "maxlength" property, until you add your own! This trick relies on adding a "maxlength" attribute to a textarea object, then wiring a function to the "onKeyPress" event which checks for the total number of characters in the Textarea each time a character is added:

<textarea rows="5" name="complaints" cols="20" maxlength="10" onkeypress="return maxLength(this)"></textarea>

The result of the check is only returned if the maxlength is less than the artificial attribute:

function maxLength(myText) {
    return myText.value.length != myText.getAttribute("maxlength");

Try the example: maxLength

Dynamic Link Submittal: You can use a link to submit a hidden form, and can even change values in a hidden field based on the link selected by the user! This is handy for dynamically generating multiple links on a page (out of a database) while still submitting the page via POST instead of GET!! First, create a form with a hidden field (or fields) and no submit button:

<form name="myForm" action="myFormHandler.php" method="post">
<input type="hidden" name="customer" value="John Doe" />
<input type="hidden" name="customerID" value="12345" />
<input type="hidden" name="toy" value="default ducky" />

Next, build a function that accepts three parameters; the name of the hidden form, the name of the hidden form field to change the value on, and the value to change it to:

function hideSubmit(thisForm,thisElement,myVal){
    thisElement.value = myVal;


Now we can load a JS function into the "onClick" event handler of each involved link:

<a href="javascript(void);" onclick="hideSubmit(myForm,myForm.toy,'froggy');">Click for a Froggy!</a>

See how this works: hideSubmit

Print this Page Back To Top

2000- <%=yere%> newMANIC INC, All rights reserved