Reputation: 4908
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
Upvotes: 0
Views: 271
Reputation: 8210
PHPJS is an excellent resource for these sorts of "How can I use this PHP function in Javascript?" questions.
Javascript htmlentities()
Upvotes: 0
Reputation: 655795
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.
Upvotes: 1
Reputation: 2937
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
Upvotes: 0
Reputation: 4908
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>');
Upvotes: 2
Reputation: 146660
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);
Upvotes: 0
Reputation: 3271
You could try replacing the < by < and > by >
var text = $('textbox').val();
text = text.replace(/</g,'<').replace(/>/g,'>');
$('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');
You can test it yourself here: http://jsfiddle.net/W7RWA/
Upvotes: 0