Event not defined in mozilla firefox for javascript function?

function onlyNumeric() { if (event.keyCode < 48 || event.keyCode > 57) { event.returnValue = false; } } onkeypress=onlyNumneric(); 

In IE, this code works fine. However, in Mozilla Firefox, the event is an undefined error.

+6
javascript cross-browser firefox internet-explorer
source share
3 answers

In FF / Mozilla, an event is passed to your event handler as a parameter. To bypass the missing event argument in IE, use the following.

  function onlyNumeric(e) { if (!e) { e = window.event; } ... } 

You will find that there are other differences between them. This link contains some information on how to determine which key is pressed in cross-browser mode.

+16
source share

Or simply, name the parameter event and it will work in all browsers. Here is a jQueryish example:

  $('#' + _aYearBindFlds[i]).on('keyup', function(event) { if(! ignoreKey({szKeyCodeList: gvk_kcToIgnore, nKeyCode: event.keyCode })) this.value = this.value.replace(/\D/g, ''); }); 

This example allows you to enter numbers only for the year fields (inside a for each loop selector), where ingoreKey () takes a keyCode list / array and compares the keyCode event and determines whether to ignore it before triggering the binding event.

The keys that I usually use for masks / others are the arrow, backspace, tabs, depending on the context / desired behavior.

You can usually also use event.which instead of event.keyCode in most browsers, at least when you use jQuery, which depends on event.which to normalize key and mouse events.

I don’t know exactly what is happening under the covers in js machines, but it seems that Mozilla FF respects a more restrictive area in which other browsers can automatically access window.event.keyCode scope on their own when the event is not explicitly passed to the function or close.

In FF, you can also access the event using window.event (as shown in some examples here), which would support this idea.

+2
source share

Some browsers may not support keyCode, you need to use keyChar

 function onlyNumeric() { var chars = event.keyCode | event.keyChar; if (chars < 48 || chars > 57) { event.returnValue = false; } } onkeypress=onlyNumneric(); 
0
source share

All Articles