Wednesday, August 24, 2011

[Javascript] Newline Character or Break Line in Textarea Field

Hi Friends,

We put a textarea to a form. Submit the form. Edit the form. Everything works fine. Textarea seems to display everything alright. But what if we want to load the form using javascript for editing?

In this case, if the text in textarea has a newline character, Javascript will throw error. Since it will be coming like this.. if text area text is  "This is my msg.\nRavi" then to javascript it will appear like
var msg = "This is my msg.
Ravi";
Which is an error.. Javascript will not do anything further. I could not find any solid solution for this but here is what can be done. I was getting the data from java so..

<%
// In java the data is stored with Html escape for all special characters etc.
msg = msg.replaceAll("\n", "<br />"); 
%>

// In javascript get the msg and replace all <br> with \n
var tmsg = "<%=msg%>";
tmsg = replaceAll(tmsg, "<br />", "\n");
tmsg = unescape(tmsg); // needed to get all special characters

Now put this content anywhere you want. 
$(#textAreaMsg).html(tmsg);

And the replaceAll function is  
function replaceAll(txt, replace, with_this) {   return txt.replace(new RegExp(replace, 'g'),with_this); }
Thats it.:)

2 comments:

Note: Only a member of this blog may post a comment.