Rajat Rajat - 1 month ago 122
PHP Question

How to Access the keycodes of special charecters in firefox browser?

We are performing front end validations by checking the keycodes of the user input. This approach is successful in chrome and Internet Explorer,but we are unable to access the keycodes in firefox browser.

function alphanumeric_only(e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (event) keycode = event.keyCode;
else if (e) keycode = e.which;
else return true;
if(
(keycode >= 48 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode >= 97 && keycode <= 122) || (keycode == 35) || (keycode == 32) || (keycode == 44) || (keycode == 45) || (keycode == 95))
{
return true;
}
else
{
return false;
}
return true;
}`


We are invoking that function from input field as follows.....

<div style="float: left;">
<input type="text" id="customname" onkeypress="return alphanumeric_only(this);" value="">
</div>

Answer

You're expicitly passing this as the argument to the function, not the event

onkeypress="return alphanumeric_only(this);"

which means e in the function is the element, not the event

function alphanumeric_only(e) {

    // "e" is the element. not the event

This still works in Chrome and IE because those browsers support the global window.event, but Firefox does not.

The solution is to pass the event as well

onkeypress="return alphanumeric_only(event, this);"

and

function alphanumeric_only(e, element) { ...

or even better, remove the inline javascript

<input type="text" id="customname" value="">

and use a proper event handler that makes this a lot easier

document.getElementById('customname').addEventListener('keypress', function(evt) {
    var keycode = evt.key || evt.which || evt.keyCode;

    if ((keycode >= 48 && keycode <= 57) || 
        (keycode >= 65 && keycode <= 90) || 
        (keycode >= 97 && keycode <= 122) || 
        (keycode == 35) || (keycode == 32) || 
        (keycode == 44) || (keycode == 45) || 
        (keycode == 95)) {

        e.preventDefault();

    }
});