0

I have a comment box(textarea) in which the user types something and when he hits enter that thing is automatically displayed in 'comment section'. Now when the user hits submit I'm executing the following code,

var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
comment.appendTo(commentSection);

By the above code the comment typed by user is dynamically displayed in the commentSection. This works fine but when user types something like,

<input type='text'>

in the comment box then a textbox is created within the comment section. So is there a way through which I could not let this happen? Thanks in advance.

3
  • 1
    Please do a google search on "input sanitization" Commented May 1, 2014 at 7:03
  • What are you trying to achieve? Commented May 1, 2014 at 7:04
  • You can use encodeURI(comment) that may do the trick. Commented May 1, 2014 at 7:04

4 Answers 4

6

One way would be to just append the data as .text

Something like this:

var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
commentSection.text(comment);

Edit: To append to an existing part of the comment, replace:

commentSection.text(comment);

with:

commentSection.text(commentSection.text() + comment);
Sign up to request clarification or add additional context in comments.

4 Comments

But this will over-write anything in the box when a second comment is added.
@RoryMcCrossan -- picky, picky. commentSection.text(commentSection.text() + comment).
@RoryMcCrossan my bad, I didn't understand the question completely, I have updated my anwser
+1 for the simplicity of your answer but the expression given by chris97ong helped me for other purposes too.
4

You have to convert the string to entities. Define this function:

function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}

Then run the following code when the user hits enter:

var comment = htmlencode($("#commentBox").val());
var commentSection = $("#commentSection");
comment.appendTo(commentSection);

Comments

2

Try this ,

div.insertAdjacentHTML( 'beforeend', comment);

Comments

2

You can use

var commentText = $("#commentBox").text();

but this do not clean html tags on your string, additionally you can use a function to do this

function RemoveHTMLTags(vals) {
            var regX = /(<([^>]+)>)/ig;
            var html = vals;
            return (html.replace(regX, ""));
        }

and then you use:

var finalComment = RemoveHTMLTags(commentText);

Comments

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.