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
ONCLICK ONLOAD ONBLUR ONMOUSEOVER ONSELECT ONFOCUS ONSUBMIT ONUNLOAD ONCHANGE
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> |
<FORM NAME="fsample"> <INPUT TYPE="button" NAME="tbut" VALUE="Click Here" onClick="alert('Got Clicked');"> </form> |