Live preview of textarea input with javascript html

烈酒焚心 提交于 2019-12-11 07:55:38

问题


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!


回答1:


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




回答2:


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




回答3:


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




回答4:


You can change with onkeyup or onchange

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



回答5:


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



来源:https://stackoverflow.com/questions/12270749/live-preview-of-textarea-input-with-javascript-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!