In my HTML page there is an input text field. I want only number key and left/right arrow on the keyboard can be entered. I tried the following JavaScript but met an issue.
<input onkeypress="return allowNumberOnly(event)" />
function allowNumberOnly(event) {
event = event || window.event;
var charCode = (event.which) ? event.which : event.keyCode;
//keyCode 48-57 represent the number 0-9
//keyCode 37,39 represent the Left and Right arrow
//keyCode 46 represent the Delete key
//keyCode 8 represent the Backspace key
return charCode == 37 || charCode == 39 || charCode == 46 || charCode == 8
|| (charCode >= 48 && charCode <= 57);
}
After testing this code, I found a problem that the keyCode of left arrow and % special character are both 37. So I can't prevent user entering % character meanwhile allowing the Left arrow. I have no idea why this would happen. I always thought the keyCode should be unique for each key on the keyboard. I thought of using onkeyup instead of onkeypress. But the onkeyup would allow user entering the invalid character first, then remove from the input text. This behavior is not what I want. Any suggestion would be appreciated.
I debugged the code in FireFox and found the following difference.
1. If enter %, event.which == 37 and event.keyCode == 0
2. If enter Left Arrow, event.which == 0 and event.keyCode == 37
The problem seems to be resolved by using this difference. I will continue to try in IE and Chrome.
This link has more info about Keyboard events
http://unixpapa.com/js/key.html
Also I made jQuery version
$('input').keypress( function( e ){
var code = e.which || e.keyCode ;
if ( !( e.shiftKey == false &&
(
code == 46 ||
code == 8 ||
code == 37 ||
code == 39 ||
( code >= 48 && code <= 57 )
)
)
){
e.preventDefault();
}
});
check it on http://jsfiddle.net/UGpUJ/
Check Bryant Williams' answer to this question:
how can i track arrow keys in Chrome and IE?
He suggests checking if the charCode==0, or checking for the shift key being pressed.
I came up with this a while ago:
var numbersOnly = function(e){
var charCode = (typeof e.which === "number") ? e.which : e.keyCode,
chr = String.fromCharCode(charCode); //convert it to a character
if(isNaN(parseInt(chr, 10))) e.preventDefault();
}
Usage:
<input type="text" name="phoneNumber" onkeypress="numbersOnly(event);">
Basically what we're doing here is getting the key code used, converting that to its char code equivalent, and then testing the char code instead of the key code. I find this method to work much better than any other I've come across and it works pretty nicely.
JS Bin Example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With