Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: keydown replicating text one character behind

Tags:

jquery

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());
});
like image 364
ps0604 Avatar asked Dec 25 '22 05:12

ps0604


1 Answers

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).

like image 58
David Thomas Avatar answered Jan 21 '23 09:01

David Thomas