ps0604
ps0604

Reputation: 1071

jQuery: keydown replicating text one character behind

The objective of this jsfiddle snippet is to display in <p/> the text entered in <input/> every time the user keys in a character. It works with the exception that <p/> is always one character behind. What's wrong with this code?

The jQuery code:

var $input = $('<input />');
$('body').append($input);
var $p = $('<p/>');
$('body').append($p);
$input.keydown(function() {
    $p.text ($input.val());
});

Upvotes: 4

Views: 1661

Answers (1)

David Thomas
David Thomas

Reputation: 253456

keydown fires as the key is pressed, and before the value is updated with the pressed key. You may wish to use keyup() instead:

$input.keyup(function() {
    $p.text ($input.val());
});

Or simplify to:

$input.keyup(function() {
    $p.text (this.value);
});

You could also manually append the last character (which works, so long as the last keypress isn't a backspace or delete:

$input.keydown(e){
    $p.val( this.value + String.fromCharCode(e.which));
});

But, frankly, that starts to become silly when you have to account for special characters (using shift, ctrl, alt or backspace and delete).

Upvotes: 10

Related Questions