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

1

6 Answers 6

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>');
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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/

2 Comments

Doing this kind of things with vanilla JavaScript kind of beats the purpose of using a framework.
This does not encode & as &amp; so the string "<&amp;>" will incorrectly encode to the HTML equivalent of the plain text string "<&>".
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);

Comments

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

Comments

0

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

Javascript htmlentities()

1 Comment

Wow, I came to the party late. Sorry!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.