2

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.

3

1 Answer 1

2

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/

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

4 Comments

aah brilliant - any thoughts on how to leave only certain tags? like bold and italics?
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.
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.
Hi, good solution but... it seems that it does not run if value is plain text without html... it generates errors. Instead a code like inputText = inputText.replace(/<\/?[^>]+(>|$)/g, ""); seems running correctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.