Page 1 of 1

[SOLVED] PHP strings with new lines into Javascript vars

Posted: Wed Mar 02, 2005 10:07 pm
by cpcd3b
Hi! This is both a PHP and Javascript question, so hopefully someone can help. Does anybody know of any way to store a PHP string variable with carriage returns into a Javascript variable and still keep the carriage returns in tact? I am using javascript to dynamically update the contents of a textarea box with the data stored in a php string based on a value selected in a select box. For strings with no carriage returns, it works fine. However, when I am echoing out the contents of the multi-line strings in PHP that need to be stored in javascript variables, javascript obviously doesn't like all the carriage returns. I HAVE to retain the formatting of the strings when they are output in the textbox. I have tried everything I can think of, but nothing seems to work. Any ideas? I am at my wits end.
Here is a code example:

<?php
$str1 = "1. This is the first line\n2. This is the second line, etc.";
$str2 = "1. This is another line\n2. And yet another line";
?>
<script type="text/javascript" language="JavaScript">
if (selectBox==1){
textbox.value="<?echo $str1;?>";
}
if (selectBox==2){
textbox.value="<?echo $str2;?>";
}
</script>

Since $str1 and $str2 contain carriage returns, when they are echoed it looks like:
textbox.value="1. This is the first line
2. This is the second line, etc.";

Javascript doesn't like this being on multiple lines. Help!

Posted: Wed Mar 02, 2005 10:30 pm
by feyd
you need to escape the \n to \\n.. str_replace can perform this action

Posted: Thu Mar 03, 2005 9:29 am
by cpcd3b
Thanks a ton feyd! I tell you, sometimes when you are so engrossed in a project/problem, you overlook the simple, logical solutions. Can't thank you enough. That's exactly what I was missing.