faressoft faressoft - 1 year ago 128
Javascript Question

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

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 */


Answer Source

Note: In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer (copy pasting that here as this answer is still getting views and upvotes):

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.

The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.

$("input").keypress(function(e) {
    if (e.which !== 0) {
        alert("Charcter was typed. It was: " + String.fromCharCode(e.which));

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.

The following was the original answer, but is not correct and may not work reliably in all situations.

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

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download