Dynamic Assignment of Event Handlers

The form below does nothing. You cannot submit it. It is only used to display how you can dynamically assign event handlers using JavaScript.

The interesting part is the entry fields below. As each gains focus, the default value is cleared. When each loses focus, if nothing is entered, the default value is restored. The really interesting part is that these event handlers are assigned dynamically when the page loads.

There are two JavaScript functions in the document head that handle the clearing and restoring of the default values:

function restoreDefault(){
   if (!this.value){
function clearDefault(){
   if (this.value==this.defaultValue){

The first function, restoreDefault, checks to see if the value is empty. If so, it sets the value to the built-in defaultValue. If it's not empty, it leaves the value as it was. The second function, clearDefault, checks to see if the current value is equal to the defaultValue and, if it is, clears the value. Click on one of the entry fields and you'll see how it works.

Okay, that's the interesting part. The really interesting part is another little script that assigns those event handlers dynamically. Why would you want to do that? It just makes life easier. If you add another entry field to the form, you don't have to worry about assigning the event handler because it's all done automatically. Here's the script that does the assignment:

function SetHandlers(){
   for(var i=0;i<document.forms.length;i++){
      for(var j=0;j<f.length;j++){
         if(c.type=="text" || c.type=="textarea"){

This script iterates through all forms on the page and through each control on the form. If the control is a text entry field, it assigns the event handlers. If you have those three functions in the <head> area of your page, you can call the SetHandlers function in your onLoad event, or (as was done on this page, place the call inside the body of the document. The only important part, if you place it in the body of the document is that it must be placed after all forms on the page.