Search code examples
javascriptfirefoxnannumerical

isNaN not working in Firefox


I have a textbox setup the following way:

<input type="text" name="CardNumber" id="CardNumber" maxlength="7" onkeypress="if(isNaN(this.value+String.fromCharCode(event.keyCode))) return false;" onblur="ValidateCardNumber()"/>

(note: ValidateCardNumber() is a separate function that checks the length among other things, but it isn't part of limiting the field to numerical values).

This works fine in IE. It will allow me to enter numbers but ignores a non-numerical keypress.

In Firefox, it I can't enter anything into that textbox.

Any thoughts?

I'm open to a different means to the end.

Thanks.


Solution

  • Debugging will show you the problem

    console.log(this.value+String.fromCharCode(event.keyCode));
    

    looking at the console you would see

    enter image description here

    So now look at what it is returning

    console.log(this.value, event.keyCode);
    

    enter image description here

    So the key code is always returning zero.

    What you need to do is use event.which for firefox

    console.log(this.value+String.fromCharCode(event.which || event.keyCode));
    

    enter image description here