Solved

Line breaks and strings in dynamic javascript code

Posted on 2006-06-19
12
1,769 Views
Last Modified: 2012-06-21
I'm building an AJAX-based site where all the content is dynamically fetched and then written to the page. Only problem is, I'm not a javascript wizard.

In this particular problem, I'm trying to build a text area with a Gmail-style Save / Discard Changes option. This text area gets written to the page, dynamically by editing the innerHTML property of a blank container as follows:

// noteID and noteText are already retrieved by making an AJAX request
// to a PHP script. The PHP script returns the noteText variable with all
// html special characters encoded, so that the quotes won't be any trouble

var qv = $('noteQuickView' + noteID);

var newInnerHTML = "<br/><div style='margin-top:2px'><img src='images/buttons/blue_block/Save_and_Close.png' alt='Save and Close' onclick='quickSave(" + noteID + ")' /> <img src='images/buttons/blue_block/Discard_Changes.png' alt='Save' onclick='quickDiscardChanges(" + noteID + ",\"" + noteText + "\")' /></div>";

qv.innerHTML = newInnerHTML;


When the noteText variable does not contain any line breaks, everything works perfectly. But when there are line breaks and I press the "Discard Changes" button, I get a javascript error. Firefox / webdev toolbar says "Unterminated string literal" but I can't figure out why. Maybe the line break is splitting the javascript code, even though it's dynamic. Is there an easy way around this? Maybe some way to escape the line breaks without messing up the data that shows up in the textarea?
0
Comment
Question by:aaron_karp
  • 4
  • 3
  • 2
  • +2
12 Comments
 
LVL 10

Expert Comment

by:Khanh Doan
Comment Utility
noteText = "\n";
I think the line break must be in " ".
Bonmat86.
0
 

Author Comment

by:aaron_karp
Comment Utility
I don't understand what you're suggesting.
0
 
LVL 30

Expert Comment

by:callrs
Comment Utility
In any PHP variables, or in the final newInnerHTML variable, replace all "\n" and "\n\r" with "<br />", before using qv.innerHTML =

For a PHP script enclosed in Javascript:
http://www.experts-exchange.com/Web/Q_21887155.html     Web Development: print php variable with javascript

For pure Javascript:
<script type="text/javascript">
function nToBR(myString){return myString.replace(/\n/g, "<br />");}
qv.innerHTML=nToBR(newInnerHTML);
</script>

(Ref: http://www.codeguru.com/forum/archive/index.php/t-350597.html, http://javascript.programmershelp.co.uk/scrolltext.php
0
 

Author Comment

by:aaron_karp
Comment Utility
But then the <br/> tags show up inside the textarea :-/

Any way around this?
0
 
LVL 5

Assisted Solution

by:shaggy_the_sheep
shaggy_the_sheep earned 150 total points
Comment Utility
Hi

I had this problem recently...

try replacing any '\n' with'\\n'
qv.innerHTML = newInnerHTML.replace(/\n/gi,"\\n"))

this is an example of what i had to do...
Original String:
document.write('<span onclick="alert(\'Hello\nWorld!\')">Hello</span>');

this produced an 'Unterminated string constant' error.

I then replaced the '\n' with '\\n' and this seemed to fix it.
document.write('<span onclick="alert(\'Hello\\nWorld!\')">Hello</span>');

Give it ago and let me know.

Richard
0
 

Author Comment

by:aaron_karp
Comment Utility
Hmm, that does fix the problem of the Javascript errors, but now the textarea shows "Testing Testing\n\nHello World!"

In other words, now the line breaks are escaped, so they're visible characters inside the textarea.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 5

Assisted Solution

by:shaggy_the_sheep
shaggy_the_sheep earned 150 total points
Comment Utility
Hi

I think the problem lies in the fact that you are setting the textarea's innerHTML, rather than its value.

Would it be possible to move the 'Save and Discard' buttons to a div, and then locate the textarea within that sme div. You could then use:

qv.value = RetrievedValue

I believe this would work better, as the escaped '\n' should now appear as new lines.

I hope this makes sense

Richard

0
 
LVL 30

Expert Comment

by:callrs
Comment Utility
Hold on, I found the answer. Back in <30 minutes.
0
 
LVL 30

Accepted Solution

by:
callrs earned 250 total points
Comment Utility
1) Enclose the textarea in a <FORM id="qvform"> tag.

2) Use:  self.document.forms['qvform'].elements['qv'].value=newInnerHTML
instead of:  qv.innerHTML = newInnerHTML;

3) Call the BRtoN function to convert all <BR> tags to "\n"
newInnerHTML=BRtoN(newInnerHTML);


For a working example, save & open this file in a browser:

<html>
<!-- Textarea multi-line javascript example
      By Ravinder Singh, 2006-06-20  -->
<!-- With help from:
http://www.codeguru.com/forum/archive/index.php/t-350597.html  "regular expressions/replace"
http://javascript.programmershelp.co.uk/scrolltext.php "Scrolling Textarea"
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace -->
<script type="text/javascript">
// Convert to & from \n <--> <br />
function nToBR(myString){return myString.replace(/\n/g, "<br />");}
function BRtoN(myString){
      myString=myString.replace(/<br.*?>/ig, "\n");
      return myString;
      }
function reset_(){
t="Line 1"
t+="<BR />Line 2"
t+="<BR>Line 3"
t+="<BR />Line 4"
t=BRtoN(t);
//document.getElementById("qv").innerHTML=t  // Doesn't work for line breaks

//self.document.forms[0].elements[0].value=t          // But this does ~!

self.document.forms["qvform"].elements["qv"].value=t;  // Tested & works in IE, Opera, Firefox

//document.getElementById("qv").value=t        // Also works in all three

}
</script>
<body onload="setTimeout('reset_()', 2000);">
<FORM NAME = "qvform" ACTION = " ">
<textarea id="qv" rows=20>
Haha
</textarea>
</FORM>
</html>
0
 
LVL 75

Assisted Solution

by:Michel Plungjan
Michel Plungjan earned 100 total points
Comment Utility
'quickDiscardChanges(" + noteID + ",unescape(\"<? echo urlencode(noteText); ?>\"))'

0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
or have the php urlencode the ajax response and just do


'quickDiscardChanges(" + noteID + ",unescape(\""+ noteText +"\"))'
0
 

Author Comment

by:aaron_karp
Comment Utility
I actually solved the problem in a different way altogether; Instead of trying to encode/escape the \n characters somehow, I simply removed the second argument from quickDiscardChanges() and then retrieve it manually from inside the function.

Still, a lot of you guys had some excellent ideas. Thanks.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now