My HTML page has an input text box. I want only the numeric key and the left / right arrow to be entered on the keyboard. I tried the following JavaScript, but ran into a problem.
<input onkeypress="return allowNumberOnly(event)" /> function allowNumberOnly(event) { event = event || window.event; var charCode = (event.which) ? event.which : event.keyCode;
After testing this code, I found that the key code of the left arrow and% of the special character is 37. Therefore, I canβt stop the user from entering the% character, while letting the left arrow go. I have no idea why this will happen. I always thought that keyCode should be unique for each key on the keyboard. I was thinking about using onkeyup instead of onkeypress. But onkeyup will allow the user to first enter an invalid character, and then remove it 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 you enter%, event.which == 37 and event.keyCode == 0
2. If you enter Left Arrow, event.which == 0 and event.keyCode == 37
The problem is apparently resolved using this difference. I will continue to use IE and Chrome.
source share