KeyCode issue - Unable to prevent% character input

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; //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 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.

+6
source share
4 answers

Check out Bryant Williams answer to this question:

How can I track the arrow keys in Chrome and IE?

He suggests checking if charCode == 0, or checking if the shift key is pressed.

+1
source

This link has more information about keyboard events.

http://unixpapa.com/js/key.html

I also made a 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 out at http://jsfiddle.net/UGpUJ/

+2
source

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(); } 

Using:

 <input type="text" name="phoneNumber" onkeypress="numbersOnly(event);"> 

We mainly use key code, converting it to the equivalent of char code, and then test the char code instead of key code. I believe that this method works much better than any other that I came across, and it works very well.

Example JS Bin.

+1
source
0
source

All Articles