Your code for normalizing the character code is incorrect. See the bottom of this answer as to why.
If you are using JQuery, it normalizes the which
property for you, so you should use event.which
to examine the pressed key. The event.which
property will be less than 32
for non-printable characters. Therefore, you should always ignore the key when event.which
is less than 32
. Otherwise, check if it is a character you want to accept.
I also think you should allow the rejected key events to bubble, so use event.preventDefault()
to reject a key, rather than return false
.
$('.commonNumber').keypress(function(event) {
var charCode = event.which;
if ((charCode >= 32) && ((charCode < 48) || (charCode > 57))) {
event.preventDefault();
}
});
jsfiddle
The code above will limit the accepted printable characters to just numeric digits, while still letting the arrow keys, the delete key, the backspace key, and other control keys to work. Key events will also bubble up, so when the Enter key is pressed, it will still submit the form (if the input element is part of a form).
If you are not using JQuery to handle the keypress event, you have to normalize the event properties yourself. According to this stackoverflow answer, you should do:
var charCode = (typeof event.which == 'number') ? event.which : event.keyCode;
Apparently all browsers, except IE<=8, support the event.which
property. In IE<=8, the event.keyCode
property holds the Unicode reference number for a printable key instead.
The issue with your original code is that in most browsers (other than IE<=8):
event.charCode
is the Unicode reference number of the character for printable keys, and 0
for non-printable keys.
event.keyCode
is a system and implementation dependent numerical code. (This is often 0
for printable keys.)
For instance, in Firefox you get:
- Ampersand key:
event.charCode = 38
and event.keyCode = 0
.
- Up arrow key:
event.charCode = 0
and event.keyCode = 38
.