Forms and Events
Monday Feb 12



Events, a light coverage

Events are actions that occur usually as a result of something the user does. For example, clicking a button is an event, as is changing a text field or moving the mouse over a link. For your script to react to an event, you define event handlers, such as onChange and onClick. The browser will monitor the page and capture certain events.

At this time, we are particularly interested in how events relate to form elements, or widgets. For example, a user may click on a button. A user may click within a text box to place the insertion point. The user may choose an item from a selection list.

Because JavaScript is object-based, it treats every HTML form element--each button, selection box, text field, and even the form itself--as a separate object containing its very own data. With JavaScript, you can examine any HTML object's data right on the user's machine and make decisions based on the results. In order to make our forms interactive, and actually do something, the widgets must respond to these events.

We can associate event handlers with many HTML elements (usually form objects and links). When an event takes place on an element, the event handler, if defined, will be called.

Event handlers are defined using JavaScript code. The code may consist of a single statement or any list of statements separated by ';'

To create an event handler for an HTML tag, add an event handler attribute to the tag. Put JavaScript code in quotation marks as the attribute value. The general syntax is

           <TAG eventHandler="JavaScript Code">
      
where TAG is an HTML tag, eventHandler is the name of the event handler, and JavaScript Code is a sequence of JavaScript statements.

By associating event handler attributes with our form elements, the widgets can respond to the user's actions and initiate some processing.

Some commonly used event handler attributes include


Putting it all together

In this demo, a form will be created. The form will contain 1 widget, a button. Each time the button is pressed, it will display a small message.

First, we will simply refresh our memory about the HTML needed to create the form.

   <FORM NAME="fsample">
      <INPUT TYPE="button" 
         NAME="tbut" 
         VALUE="Click Here"> 
   </FORM>
   

Now, we need to figure out a few details.

How will we report the results to the user?

Using the confirm() function

   <FORM NAME="fsample">
      <INPUT TYPE="button" 
      NAME="tbut" 
      VALUE="Click Here"
      onClick="confirm('Got Clicked');">
   </FORM>
   
            


Using the alert() function

   <FORM NAME="fsample">
      <INPUT TYPE="button" 
      NAME="tbut" 
      VALUE="Click Here"
      onClick="alert('Got Clicked');">
   </form>