I’m building a comment module for my web application.
In the application I need commenting. When a user posts a comment, I would like jQuery to grab the TextArea’s value and then insert it into the page <p>. Problem is that when it inserts the contents it loses the HTML formatting, mainly page breaks/returns which confuses users. How can I fix the code to retain the HTML styling?
Snippets:
comments.js
var textsubmitted = $("#write-new-comment-textarea").val();
var commentStr = '<li><div class=\"comment-header\"><span class=\"comment-avatar\"><a href=\"/user-view/' + data.personid + '/\"><img src=\"' + data.profilepicsrc + '\" /></a> </span><span class=\"comment-author\"><a href=\"/user-view/' + data.personid + '/\"> <b>' + data.personname + '</b> </a></span><span class=\"comment-timestamp\">just now</span> </div><div class=\"comment-body\"><p>' + textsubmitted + '</p></div></li>';
Thanks
You need to escape your textsubmitted string . If you set the text property of a div , jquery automatically does that . So you can build only the HTML part of your commentsStr , append it to dom and then assign it the text value later .