1

If i write something like below inside textarea

<strong>test</strong>

inside textarea and then display it inside a div. It shows the text in bold letter instead of showing the html code as it is. So how can i avoid rendering html code. I just want to show as it is the text was entered by user.

Shimmy Weitzhandler
  • 97,705
  • 120
  • 409
  • 613
Manish Kumar
  • 9,824
  • 21
  • 74
  • 137
  • http://jsfiddle.net/WPQLP/1/ I can't replicate your error. – Madthew May 08 '13 at 16:30
  • @Madthew — Since your attempt to replicate it doesn't include a textarea or a div and doesn't do anything to place what is typed in said textarea into said div, that isn't surprising. – Quentin May 08 '13 at 16:31
  • http://jsfiddle.net/WPQLP/2/ so it should work now. Forgot to update dhe jsfiddle. – Madthew May 08 '13 at 16:33
  • @Madthew — The question says "I just want to show as it is the text was entered by user" and "display it inside a div" — Your example hard codes the data into the textarea (so not entered by the user) and doesn't display it in a div at all. – Quentin May 08 '13 at 16:35

5 Answers5

3

You haven't shown us any code, but since you have tagged this jQuery I'll assume you have something like:

$('div').html(
     $('textarea').val()
);

Use the text method instead, so what the user has typed is treated as text instead of HTML.

$('div').text(
     $('textarea').val()
);

See a demonstration.

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
2

you'll need to escape the html formatting

this should work

var someHtmlString = "<strong>test</strong>";
var escaped = $("div.someClass").text(someHtmlString).html();

source

Community
  • 1
  • 1
Jean-Bernard Pellerin
  • 12,351
  • 9
  • 57
  • 76
2

You can use the <pre> tag so that it shows the user input as is. This preserves all formatting such as spaces and newlines

<textarea  rows="4" cols="50"></textarea>
<div>
   <pre id="output">
   </pre>
</div>  

js

$('textarea').keyup(function(){
$('#output').text($(this).val()); 
});

http://jsfiddle.net/WPQLP/5/

1

You need to escape the < and > characters to their HTML entities.

&lt;strong&gt;test&lt;/strong&gt;

JSFiddle

epascarello
  • 195,511
  • 20
  • 184
  • 225
0

&lt;strong&gt;test&lt;/strong&gt; produces <strong>test</strong>

These are called HTML entities and behave like that because normally <foo> means a HTML tag, and it's supposed to be rendered. Read more about HTML entities on w3schools

Mateusz
  • 3,006
  • 4
  • 26
  • 41