2

I'm using javascript/jQuery.. on the keydown of an input[type='text'] I receive a key code. I need to determine whether it's a character code or a command code because I need to know whether the input will change. I cannot use the change event as this event is postergated until the element loses focus.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243

4 Answers4

2

You should be able to use event.ctrlKey, event.altKey and event.shiftKey, etc. in your event handler.

Also check the Ascii table, you could check that the keycode is between 33 & 127, for example, to check for a-z, numbers and punctuation characters (missing out space, del, enter, etc.)

Clive
  • 36,918
  • 8
  • 87
  • 113
  • This is not reliable. Only the `keypress` event can tell you anything reliable about the character typed. – Tim Down Oct 11 '11 at 23:12
2

Rather than fiddle with keycodes, why not just keep a cached copy of the value in memory and just compare (and update if necessary) every time a key is pressed:

var the_value = $('#the-input').val();
$('#the-input').keyup(function(ev) {
    if (the_value != $(this).val()) {
        the_value = $(this).val();
        // input has changed, act on event here
    }
});
Rob W
  • 341,306
  • 83
  • 791
  • 678
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • `Keyup` instead of `keydown`. The contents of the text field hasn't changed yet when the `keydown` event is fired. – Rob W Oct 11 '11 at 17:38
0
switch (e.keyCode) {
// up                                                                         
case 38:
break;
// down                                                                        
case 40:
break;
// esc                                                                         
case 27:
break;
// enter                                                                         
case 13:
break;
}

Look for javascript keycodes in Google to get the complete list. The javascript keycodes are not entirily cross browser consistent.

  • Try using `e.which` instead of `e.keyCode`, jQuery normalizes the `e.which` so it is more consistent across browsers. – Mottie Oct 11 '11 at 17:36
  • Only the `keypress` event can tell you anything reliable about the character typed (using the `which` property of the event). @fudgey: in the `keyup` and `keydown` events, `keyCode` is the correct property. – Tim Down Oct 11 '11 at 23:15
0

The short answer is that you simply cannot reliably detect whether a keystroke corresponds to typing a printable character in the keydown or keyup events (which are only concerned with physical keys). For anything to do with detecting the character typed, use the keypress event instead.

However, it sounds like what you actually need is the HTML5 input event. See my answer here:

Catch only keypresses that change input?

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536