You've got three key-related events to choose from, keyup
, keydown
and keypress
; assuming you type the string abc
:
$('#demo').on('keyup', function(e){
console.log(this.value);
});
// a
// ab
// abc
JS Fiddle demo.
$('#demo').on('keydown', function(e){
console.log(this.value);
});
//
// a
// ab
JS Fiddle demo.
$('#demo').on('keypress', function(e){
console.log(this.value);
});
//
// a
// ab
JS Fiddle demo.
The difference is, as the output (roughly) shows, is that keyup
and keypress
respond before the value of the element is updated; so if you want to know the key that was pressed you have to use e.which
(the jQuery normalized keypress event which returns the keyCode
of the pressed-key) in both the keypress
and keyup
handlers and then add that to the value
property. e.which
will, under keyup
also return the correct keyCode
, but you don't have to manually add that key to get the updated value
.