6

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.

kimi
  • 87
  • 1
  • 9

4 Answers4

2

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/

rab
  • 4,134
  • 1
  • 29
  • 42
1

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.

Community
  • 1
  • 1
jeremy
  • 9,965
  • 4
  • 39
  • 59
  • The OP also wants to allow `<` and `>` keys (hence the issue with `%`). – Jared Farrish Mar 30 '13 at 05:32
  • @JaredFarrish Ah, see in Chrome the arrow keys worked, though testing it in Fx I see that they don't. – jeremy Mar 30 '13 at 05:36
  • I suspect it's because Firefox sees `<` and `%` as [flipped `.keyCode` and `.charCode`](http://jsfiddle.net/userdude/mvJD5/1/). Chrome appears to ignore `<` presses. – Jared Farrish Mar 30 '13 at 06:02
  • Hm.. maybe. It seems very odd. (Sidenote: `<` and `>` made me think you were talking about chevrons, so for future readers: don't think that.) – jeremy Mar 30 '13 at 06:04
  • @Nile your fiddle works okay in jsbin but its not working in jsfiddle http://jsfiddle.net/vnodkumar1987/uhufp/2/ (have added radix parameter) – exexzian Mar 30 '13 at 06:32
  • @Bingo On the lefthand side of the page click "Frameworks & Extensions", then click on where it says "onLoad" and change it to the "in " option. – jeremy Mar 30 '13 at 06:33
  • @Bingo I have absolutely no idea what you're asking, but I'm almost positive it's off topic. – jeremy Mar 30 '13 at 06:40
  • @NIle I am asking about that option part. how to to do that in file not using that jsfiddle option – exexzian Mar 30 '13 at 06:45
  • Since when does `fromCharCode` work with key codes, which are not the same thing? – ErikE Mar 30 '13 at 06:57
  • @ErikE I was under the impression that they were =/. [keyCode](https://developer.mozilla.org/en-US/docs/DOM/event.keyCode) returns a Unicode value, [fromCharCode](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/fromCharCode) returns a string created by a Unicode value... check MDN – jeremy Mar 30 '13 at 07:06
  • @Nile I tested your code both in Chrome and FireFox. In Chrome, the Left/right arrow keys worked, but in FireFox they don't. – kimi Mar 30 '13 at 08:10
1

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.

Community
  • 1
  • 1
pkExec
  • 1,752
  • 1
  • 20
  • 39
  • @Nile Adding the event.shiftKey == false do exclude the % character, but it also prevent me entering the combination key Shift + Left. I'd like to use this combination key to select the content in the input text field. – kimi Mar 30 '13 at 07:50
0

Use onKeydown event. For % it is 53.

Check this links for keycode checking: http://kyokodaniel.com/tech/utils/keycodes.html

http://www.west-wind.com/WestwindWebToolkit/samples/Ajax/html5andCss3/keycodechecker.aspx

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
sasi
  • 4,192
  • 4
  • 28
  • 47