views:

92

answers:

3

Is there a built-in jQuery function for encoding a string as HTML?

I'm trying to take the text a user types into a text box and then put that text into a different area of the page. My plan was to take the .val() from the text box and supply that to the .html() of the <div> element. Perhaps there's a good jQuery plugin to help with this (if it's not built-in) or a better way overall to accomplish this goal.

For example, if the user puts <Victory!> in the text box, I'd want the other part of the page to actually show the text <Victory!> instead of nothing being visible.

+3  A: 

Instead of .html() use .text() for this. This will encode the output when putting it in the destination element. Here's a quick demo showing the differences, try something like "<script>": http://jsfiddle.net/6WG47/

Nick Craver
what kind of DOM element will accept a `.text()` method call? When I try to change `$('#ResultsContainer').html(htmlBody)` to `$('#ResultsContainer').text(htmlBody)` I get an error message that "the object doesn't support this property or method."
Ben McCormack
@Ben - What is `#ResultsContainer`? Anything that accepts text inside should accept `.text()` I added a demo showing both being used from the same input value, see if that helps any at all.
Nick Craver
@Nick good question. It's a `<div>` element
Ben McCormack
@Ben - `htmlBody` is a string correct? If that's the case do you have an page I can access/look at?
Nick Craver
@Nick it was my mistake....I had an invalid function call somewhere else. Your method worked perfectly.
Ben McCormack
A: 

If the .val() contains HTML markup (i.e. text), that should automatically render if you pass it directly to .html(). Are you experiencing something otherwise? Or are you wanting to strip the html encoding?

BradBrening
+1  A: 

What about using the JavaScript escape function for this? I think that makes the most sense.

brendan
@brendan The JavaScript `escape` function will encode the data to work in a URL, not HTML.
Ben McCormack