admin管理员组

文章数量:1430648

I'm trying to get contents between the <pre>...</pre> tag to be rendered by JavaScript, where the contents is dynamic. What I hope to do is to type an input within a textarea to update display in the <pre> tags.

I'm unsure how to specify the contents within the <pre> tags to take the value from textarea on every textarea update.

Many Thanks!

I'm trying to get contents between the <pre>...</pre> tag to be rendered by JavaScript, where the contents is dynamic. What I hope to do is to type an input within a textarea to update display in the <pre> tags.

I'm unsure how to specify the contents within the <pre> tags to take the value from textarea on every textarea update.

Many Thanks!

Share Improve this question edited Aug 23, 2012 at 15:52 Roddy of the Frozen Peas 15.3k10 gold badges59 silver badges106 bronze badges asked Aug 23, 2012 at 15:43 XinYi ChuaXinYi Chua 2811 gold badge6 silver badges17 bronze badges 2
  • 4 Okay, so what exactly have you tried? This site is more for specific problems you e across, rather than a site where we write tutorials for you. – MetalFrog Commented Aug 23, 2012 at 15:45
  • Hi maybe I was too hasty in posting my question, I was trying to get an alternative answer from using innerHTML. I got my question answered. Thanks. – XinYi Chua Commented Aug 24, 2012 at 11:33
Add a ment  | 

2 Answers 2

Reset to default 5

Seeing the code you're working with would help greatly, but if I'm reading correctly, this should help. Assuming HTML like this:

<textarea id="type"></textarea>
<pre id="output"></pre>

This option uses pure javascript:

var textarea = document.getElementById('type'),
    pre = document.getElementById('output');

if(textarea.addEventListener) {
    textarea.addEventListener('keyup',function(){
        pre.textContent = this.value;
    });
} else {
    textarea.attachEvent('onkeyup',function(){
        pre.textContent = this.value;
    });
}

This code block uses the jQuery library for brevity:

$('#type').on('keyup',function(){
    $('#output').text($(this).val());
});

Note that in both situations, I am setting the text of the <pre>, not the HTML. This allows you to enter HTML characters like < into the textarea and have them be properly escaped in your <pre> element.

Pure JavaScript Demo

jQuery Demo

If you don't wish to change the <pre> until after you leave the <textarea>, then just change 'keyup' and 'onkeyup' to 'change' and 'onchange' respectively.

Bind the onchange event to the input, and then simply copy its value to pre:

<pre id="pre">Type something</pre>
<textarea id="text" rows="20" cols="20" />
​
<script type="text/javascript">
document.getElementById("text").onchange = function () {
  document.getElementById("pre").innerHTML = this.value;  
};
</script>

DEMO.​

本文标签: javascriptChange ltpregt block contents upon textarea updateStack Overflow