codelove
codelove

Reputation: 2016

Live preview of textarea input with javascript html

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

Answers (5)

Anil
Anil

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>​

Check out this JSFiddle

Upvotes: 3

Jayesh Pawar
Jayesh Pawar

Reputation: 175

onkeyup event in javascript will take the letter as soon you press it

Upvotes: 0

Musa
Musa

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;
}​

DEMO

Upvotes: 11

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can change with onkeyup or onchange

onkeyup ="document.getElementById('prevCom').innerHTML = this.value"

Upvotes: 0

Kishore
Kishore

Reputation: 1912

Try this

<textarea name="WPcomment" id="WPComment" placeholder="Add comments:" onkeyup="document.getElementById('prevCom').innerHTML = this.value"></textarea>

<div id="prevCom"></div>​

Use onkeyup instead of onkeypress

here is the demo

Upvotes: 0

Related Questions