1

If i get the .val() from a text input, how can I make sure there is no HTML in there and just plain text?

I am writing a small chat program but I dont want users to be able to enter HTML.

Chud37
  • 4,907
  • 13
  • 64
  • 116

1 Answers1

1

You can do it by getting the textContent of the HTML they enter:

// Get the value of the input
var inputText = $('#my-input').val();
// Store only the text and no HTML elements.
inputText = $(inputText)[0].textContent;

Here is an example:

http://jsfiddle.net/thom801/5A3sQ/1/

thomallen
  • 1,926
  • 1
  • 18
  • 32
  • aah brilliant - any thoughts on how to leave only **certain** tags? like bold and italics? – Chud37 Aug 01 '12 at 16:56
  • You would probably need to learn some regex at that point. It would be really difficult I think. Maybe a WYSIWYG editor would work well for what you are doing? There are some really lightweight ones. – thomallen Aug 01 '12 at 17:48
  • Well. You could use a combination of .html() and .each too to whitelist tags. It will get a little complicated when the tags are nested but not impossible. – Joel Peltonen Oct 15 '13 at 10:23