1. Home
  2. Computing & Technology
  3. JavaScript

Learn Javascript

Form Events

Join the Discussion

Questions? Comments?

Related Terms

Event

Introduction

When you are adding event handlers to your forms you will often use a lot of the same event handlers that we have already looked at, particularly the onfocus and onblur event handlers. The onblur event is particularly useful to allow a field to be validated immediately after it has been entered.

In this tutorial we are going to look at a couple of event handlers that only get used with forms.

Onsubmit and Onchange

The onchange() event handler is triggered whenever the content of a form field is changed. The form field where this is most useful is for drop down selection lists since by using onchange instead of onblur the field can be tested immediately rather than waiting for a different field to be selected.

The onsubmit() event handler is attached to the form tag itself. Whenever a submit button is selected (or the submit method for the form is called from within your Javascript code) this event will be triggered.

Here is a sample form to demonstrate how these events are triggered:

Here is the code for the above form with the tag names and the event handlers shown in bold.

<form name="ex" method="POST"
onsubmit="alert('onsubmit');return false;">
<div align="center">
<select name="sel" size="1"
onchange="alert('onchange')">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" value="submit" />
</div></form>

Onreset

The onreset() event handler (like onsubmit) is attached to the form itself. This event is triggered if the form contains a reset button and that button is pressed.

Using What You Know

You now know sufficient Javascript to be able to understand the form field validation tutorials that will take you step by step through the creation of validation routines that are as simple or as complex as they need to be to validate the fields on your forms for the values that you decide are allowed to be entered.

Past Lessons

  1. Introduction
  2. Decision Making
  3. Functions
  4. Maintain and Test
  5. External Script and Noscript
  6. Object Oriented Javascript
  7. Loops
  8. More Predefined Classes
  9. Document Object Model
  10. Event Handlers
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.