Detect real “hard” character keys only

Posted on

Problem

Is there any simple way to detect user keystrokes that result in character input? In other words, ignore all soft keys and modifier keys? This works but seems sort of hacky:

var keycode = event.keyCode ? event.keyCode : event.charCode
if((keycode>=48 && keycode<=90) || (keycode>=96 && keycode<=111) || (keycode>=186 && keycode<=192) || (keycode>=219 && keycode<=222)){
    alert("realkey")
}

Solution

Yes, use keypress events instead of keydown events. See example: http://jsfiddle.net/7fmjh/6/ – or a non-jquery example: http://jsfiddle.net/7fmjh/11/

You can use String.fromCharCode in combination with a Regular Expression test as alernative:

var cando =  /[a-z0-9]/i
              .test(String.fromCharCode(event.keyCode || event.charCode));
if( cando ){
    alert("realkey")
}

In the RegExp you can put all the characters you want to allow, in this case all a to z (case insensitive) and the digits 0 to 9. Best to use the keypress event here.

BTW, what kind of criterium is ‘seeming sort of hacky’?

Leave a Reply

Your email address will not be published. Required fields are marked *