Solved

Line breaks and strings in dynamic javascript code

Posted on 2006-06-19
12
1,776 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +2
12 Comments
 
LVL 10

Expert Comment

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

Author Comment

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

Expert Comment

by:callrs
ID: 16940381
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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 

Author Comment

by:aaron_karp
ID: 16940403
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
ID: 16940481
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
ID: 16940566
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
 
LVL 5

Assisted Solution

by:shaggy_the_sheep
shaggy_the_sheep earned 150 total points
ID: 16940674
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
ID: 16940932
Hold on, I found the answer. Back in <30 minutes.
0
 
LVL 30

Accepted Solution

by:
callrs earned 250 total points
ID: 16941136
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
ID: 16941541
'quickDiscardChanges(" + noteID + ",unescape(\"<? echo urlencode(noteText); ?>\"))'

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 16941568
or have the php urlencode the ajax response and just do


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

Author Comment

by:aaron_karp
ID: 16946125
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
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…

696 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