Wednesday, November 17, 2010

"Event is Not Defined" Error in Firefox

This error may occur when you try to attach a JavaScript function dynamically to page elements and pass an event to the function. An example:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].type == 'text') {
        inputs[i].onkeypress = function() { return isNumericKey(event); }
    }
};

Here is a listing of the validation function:


/* Numeric Validation */
function isNumericKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode >= 48 && charCode <= 57 || charCode == 46) {
        return true;
    }
    else {
        return false;
    }
}
 
This code will work perfectly in IE and it won't allow users to type any other characters than numeric. However, in Firefox, it will throw an error: "event is not defined".

First solution:

Check whether the event is defined in Firefox and attach a reference to the validation function.

if (typeof (event) == "undefined")
    inputs[i].onkeypress = isNegativeNumericKey;
else
    inputs[i].onkeypress = function() { return isNumericKey(event);}

In this case, the event is a global variable that does not exist in Firefox. We could have rewritten the type check as follows:

if (typeof (window.event) == "undefined") ...

Second solution:

Use the following version of the function call in Firefox by passing the event parameter to the function that handles the keypress event:

inputs[i].onkeypress = function(event) { return isNumericKey(event);}

But this would not work in IE.  The solution: normalize the Event interface in the function body:

function(event) { 
   event = event || window.event;
   return isNumericKey(event); 
}

3 comments:

  1. Thank you much you solved my problem you r really a genius guy thanks so much your code is rock buddy

    ReplyDelete
  2. very good. you solved my problem.

    Thank you very much.

    ReplyDelete