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?

5
  • 1
    Use text() to add the variable to a DOM element - assuming you want to HTMLEncode the value, not strip out the HTML completely. Commented Feb 13, 2015 at 15:58
  • possible duplicate of How to strip HTML tags with jQuery? Commented Feb 13, 2015 at 15:58
  • 1
    Why is this downvoted? OP has given an description of the issue and asked a legitimate question. Commented Feb 13, 2015 at 16:00
  • Duplicate and it was answered Escaping HTML strings with jQuery Commented Feb 13, 2015 at 16:01
  • I see that this could be related to the suggested question. However, there are serious critics about the recommend solution. Commented Feb 13, 2015 at 16:04

2 Answers 2

5

This works for me:

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

Result:

aby&lt;d

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

Sign up to request clarification or add additional context in comments.

Comments

0

You could use:

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

3 Comments

$($(this).val()).text(); Uncaught Error: Syntax error, unrecognized expression: aby<d at Function.Sizzle.error (jquery-3.3.1.js:1541) at Sizzle.tokenize (jquery-3.3.1.js:2193) at Sizzle.select (jquery-3.3.1.js:2620) at Function.Sizzle [as find] (jquery-3.3.1.js:845) at jQuery.fn.init.find (jquery-3.3.1.js:2873) at new jQuery.fn.init (jquery-3.3.1.js:2983) at jQuery (jquery-3.3.1.js:139)
@alexqc error comes from value you are trying to parse
Yes, I'm trying to encode html character from input containing text "aby<d", and jquery fails using this $($(this).val()).text(); approach to encode.