0

Here i have a textbox in which user inputs html tags like <h1>hello</h1> then i append that text to a td with

 var text = $('textbox').val();
 $('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');

Now what i want is the text in the td should come text as entered <h1>hello</h1> and not hello with h1 tag

I tried escape and unscape but it didnt helped

eldarerathis
  • 35,455
  • 10
  • 90
  • 93
jimy
  • 4,848
  • 3
  • 35
  • 52

6 Answers6

2

Used encode function from here HTML-encoding lost when attribute read from input field

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

 var text = htmlEncode($('textbox').val());
 $('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');
Community
  • 1
  • 1
jimy
  • 4,848
  • 3
  • 35
  • 52
1

Here’s a plain JavaScript function without the jQuery overkill:

function htmlEncode(str) {
    return str.replace(/[<>&"']/g, function($0) { return "&" + {"<":"lt",">":"gt","&":"amp",'"':"quot","'":"#39"}[$0] + ";"; });
}

This looks for any occurrence of <, >, &, ", and ', calls the function that then looks up the matched character and returns the corresponding character reference.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

You could try replacing the < by &lt; and > by &gt;

var text = $('textbox').val();
text = text.replace(/</g,'&lt;').replace(/>/g,'&gt;');
$('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');

You can test it yourself here: http://jsfiddle.net/W7RWA/

Mark
  • 3,231
  • 3
  • 32
  • 57
0

You need to set the node value with the val() method:

// Untested
var text = $('textbox').val();
var tr = $('<tr><td style="padding:0px 12px;color:black"></td></tr>');
tr.find("td").val(text);
$('table').append(tr);
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

if you want html_entities ....

try the phpjs project

https://github.com/kvz/phpjs/blob/master/functions/strings/htmlentities.js

.. it also requires this function though https://github.com/kvz/phpjs/blob/master/functions/strings/get_html_translation_table.js

Bruce Aldridge
  • 2,907
  • 3
  • 23
  • 30
0

PHPJS is an excellent resource for these sorts of "How can I use this PHP function in Javascript?" questions.

Javascript htmlentities()

dtbarne
  • 8,110
  • 5
  • 43
  • 49