简体   繁体   中英

Loading multiline text from database to TextArea

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>";

PS FillElements function:

function FillElements(Sub,Txt)
        {
            document.getElementById('txtSubject').value=Sub;
            document.getElementById('txtMessage').value=Txt;
        }

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)
);

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...

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:

http://jsfiddle.net/wFZWQ/


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM