Reputation: 2016
Hi I am setting up a live preview of the input of a textarea which will be posted to a blog. I currently have this set up
<textarea name="WPcomment" id="WPComment" placeholder="Add comments:" onkeypress="document.getElementById('prevCom').innerHTML = this.value"></textarea>
<div id="prevCom"></div>
The issue is that the preview is one character behind the input of the textarea. For instance if i write "my comment" I see "my commen"
Thanks for your help!
Upvotes: 1
Views: 11334
Reputation: 21910
Instead of onkeypress="..."
Change to onkeyup
. This will fix the issue your having with the with the characters not updating as expected.
So your final code should be:
<textarea name="WPcomment" id="WPComment" placeholder="Add comments:" onkeyup="document.getElementById('prevCom').innerHTML = this.value"></textarea>
<div id="prevCom"></div>
Upvotes: 3
Reputation: 175
onkeyup
event in javascript will take the letter as soon you press it
Upvotes: 0
Reputation: 97672
Use keyup and keypress events, keyup alone won't work if someone holds down a key and it repeats.
var wpcomment = document.getElementById('WPComment');
wpcomment.onkeyup = wpcomment.onkeypress = function(){
document.getElementById('prevCom').innerHTML = this.value;
}
Upvotes: 11
Reputation: 28970
You can change with onkeyup or onchange
onkeyup ="document.getElementById('prevCom').innerHTML = this.value"
Upvotes: 0