Reputation: 2956
I have some multi line text saved in MySql database (VARCHAR 255). When i load it, and process it using standard php function "nl2br", it echoes fine (multi line). But, when i load multi line text from database, make it "nl2br" and then send it to javascript (so it gets displayed in textarea), it won't be displayed! What's wrong?
echo "<SCRIPT>FillElements('".$subject."','".$text."');</SCRIPT>";
P.S. FillElements function:
function FillElements(Sub,Txt)
{
document.getElementById('txtSubject').value=Sub;
document.getElementById('txtMessage').value=Txt;
}
Upvotes: 1
Views: 3836
Reputation: 1856
textarea
s don't actually store the contents in an attribute like value
in the same manner as input elements. They actually store the contents in in between the <textarea>
and </textarea>
tags. Meaning that the contents is actually treated as CDATA in the document.
<textarea>
This is my Content
</textarea>
Produces a text area with "This is my Content" as the contents.
The implication of this is that you cannot use the code you have to alter the contents of a textarea. You have to alter the innerHTML property of the textarea. I have set up a simple example here:
As an aside, since you are populating the fields using PHP on the creation of the page, why not merely fill the data in the HTML markup, this seems like a long way round to do it.
Also, since you don't appear to be using it, have you seen [jQuery][1] it abstracts alot of things out, so instead of typing document.getElementById("the_id")
to get an element you can use CSS selectors and merely write $("#the_id")
to get the same element. You also get a load of useful functions that make writing javascript mucxh easier.
[1]: http://jquery.com jQuery
Upvotes: 1
Reputation: 185933
My guess is that your HTML source code looks like this:
<script>FillElements("foo","foo
bar
baz");<script>
Correct?
In JavaScript, strings cannot span multiple lines...
Upvotes: 0
Reputation: 34632
Newline tags (<br />
) don't cause actual new lines in <textarea>
.
You can pass the "real" newlines (\n
) to your <textarea>
, though.
I created a fiddle for that.
EDIT: For the updated FillElements
code:
$subject = "String\nWith\nMultiple\nLines";
printf('<script type="text/javascript">FillElements(%s)</script>',
json_encode($subject)
);
Upvotes: 0