0

Using jQuery, I am capturing the text input of a form using .val():

$newItem = $('input[type=text]').val();

The problem is that .val() will preserve any html-tags, which will be applied in the DOM if I am appending the variable.

What is the recommended, safe way to escape HTML-input and just use the text value?

  • 1
    Use `text()` to add the variable to a DOM element - assuming you want to HTMLEncode the value, not strip out the HTML completely. – Rory McCrossan Feb 13 '15 at 15:58
  • possible duplicate of [How to strip HTML tags with jQuery?](http://stackoverflow.com/questions/13140043/how-to-strip-html-tags-with-jquery) – Aditya Feb 13 '15 at 15:58
  • 1
    Why is this downvoted? OP has given an description of the issue and asked a legitimate question. – Rory McCrossan Feb 13 '15 at 16:00
  • Duplicate and it was answered [Escaping HTML strings with jQuery](http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery) – Fares M. Feb 13 '15 at 16:01
  • I see that this could be related to the suggested question. However, there are serious critics about the recommend [solution](http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery). –  Feb 13 '15 at 16:04

2 Answers2

4

This works for me:

$("<div>").text($('input[type=text]').val()).html()

Result:

aby&lt;d

Fiddle: https://jsfiddle.net/xpvt214o/851964/

alexqc
  • 547
  • 4
  • 9
0

You could use:

$newItem = $($('input[type=text]').val()).text();
A. Wolff
  • 74,033
  • 9
  • 94
  • 155