views:

65

answers:

3

How to know if .keyup() is a character key (jQuery)

$("input").keyup(function() {

if (key is a character) { //such as a b A b c 5 3 2 $ # ^ ! ^ * # ...etc not enter key or shift or Esc or space ...etc
/* Do stuff */
}

});
+1  A: 

If you only need to exclude out enter, escape and spacebar keys, you can do the following:

$("#text1").keyup(function(event) {
if (event.keyCode != '13' && event.keyCode != '27' && event.keyCode != '32') {
     alert('test');
   }
});

See it actions here.

You can refer to the complete list of keycode here for your further modification.

Lee Sy En
not enter key or shift or Esc or space ...((((((etc))))))
faressoft
+1  A: 

To match the keycode with a word character (eg., a would match. space would not)

$("input").keyup(function(event)
{ 
    var c= String.fromCharCode(event.keyCode);
    var isWordcharacter = c.match(/\w/);
}); 

Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this article in quirksmode.

Nivas
On Firefox keyCode for F1 key and P keys is the same (also F2 is 'q', F3 is 'r' etc.). On Chromium (Webkit browser) F1 is 'P', F2 is 'Q' etc.
hluk
You can't get the character typed reliably from the `keyup` event. This may work on your keyboard but for different keyboard types and different cultures there are no guarantees at all.
Tim Down
+1  A: 

You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.

keyup and keydown give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between the keyCode property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.

Tim Down