简体   繁体   中英

Escape HTML tag in <textarea>

I have one <textarea> tag in my website where the user can put there HTML code and see its preview. My problem is when the user enter code below mention in my <textarea> my preview functionality getting fail :

<html>
<textarea>Some code to show</textarea>
</html>

So question is how can I escape this html code in my <textarea> tag as I know the problem is coming because </textarea> tag .

Any solution on this please.

Edit

Question is about using </textarea> within a textarea.

Problem visible here: http://jsfiddle.net/hrP6F/

EDIT: for your purpose this would do:

<textarea>
        Outside Textarea
        &lt;textarea&gt;Inside Textarea&lt;/textarea&gt;
</textarea>

source: How can I embed a textarea inside of another textarea in HTML?

Or use contenteditable like someone already mentioned -> click

FIRST ANSWER: Im not sure I understand perfectly but still. You want to display the code inside text area somewhere else for instance?

You could do that on click like this (I reckon you are not statically putting nested text areas in html?):

HTML:

<textarea id="textarea" >Something code to show</textarea>
<button onclick="show()">show</button>
<div id="showArea"></div>

JS:

function show(){
    var t = document.getElementById('textarea').value; 
    document.getElementById('showArea').innerHTML = t;
}

This is of course if what you want is to display html that is inside textarea. you could also put another textarea inside first one and it will work.

If you want the results to display dynamically you could use

<textarea id="textarea" onkeyup="show()">Something code to show</textarea>

This works even if you put your code (html and text area) inside text area - it displays it, I tested it

You can add a output div for preview purpose. Below is the jQuery script

HTML

<textarea placeholder="Enter your html"><b>test</b></textarea>
 <a href="#" class="run">Run</a>
  <div class="op"></div>

JS

 $('.run').click(function(){
    $('.op').html($('textarea').val());
    return false;
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM