简体   繁体   中英

html encode <textarea> value

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

Try 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM