最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - html encode <textarea> value - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 2

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.

发布评论

评论列表(0)

  1. 暂无评论