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());
});
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With