How do I get the latest updated typed in value of a textarea and html encode the value.
To get the value I use:
$('textarea').val(); // this works cross browser
But if the value was "sdfgsdgdsgsdg <br/>"
how do I HTML encode it?
It breaks when I stringify()
it
var e = { "d" : $('textarea').val()};
var s = JSON.stringify(e); //it breaks here
How do I get the latest updated typed in value of a textarea and html encode the value.
To get the value I use:
$('textarea').val(); // this works cross browser
But if the value was "sdfgsdgdsgsdg <br/>"
how do I HTML encode it?
It breaks when I stringify()
it
var e = { "d" : $('textarea').val()};
var s = JSON.stringify(e); //it breaks here
Share
Improve this question
edited Aug 10, 2012 at 12:40
Hello-World
asked Aug 10, 2012 at 12:13
Hello-WorldHello-World
9,55524 gold badges90 silver badges157 bronze badges
4
-
4
var s = {"a":"sdfgsdgdsgsdg <br/>"};
does not error (nor is it JSON, it is JavaScript) – Quentin Commented Aug 10, 2012 at 12:15 - 1 you may find this useful stackoverflow./questions/1219860/… – Senthil Kumar Commented Aug 10, 2012 at 12:18
- You HTML encode strings to make them HTML friendly, not JSON friendly. – Quentin Commented Aug 10, 2012 at 12:30
- What is your expected output? – wirey00 Commented Aug 10, 2012 at 13:43
2 Answers
Reset to default 2Try the following.
var string = $('textarea').val();
var encoded = $('<div/>').text(string).html();
demo
it break here
That isn't a very helpful description of the error, but I'm guessing you mean I get an empty object.
Spell textarea
correctly (it doesn't have an e
in the middle), so that you assign the value of the textarea instead of undefined
(which is what you get when you call val()
on an empty jQuery object).
This has nothing to do with HTML encoding. HTML isn't involved in this process at all. You take user input from a DOM, and then put it into JSON. JSON.stringify takes care of all your encoding needs.