Search code examples
javascriptkeycode

keyCode issue - Can't prevent entering the % character


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.


Solution

  • 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.