简体   繁体   中英

Textarea issues when retrieving data with line breaks inside javascript code

A lot of queries raised targeting this issue. ie line breaks within a textarea attribute.

I tried to use str_replace("<br />", "\\n",$text) within a javascript variable where I got it working within a php code. Unfortunatley had no such luck with the methodology I am using within the javascript code.

The code I am trying to use is as follows:

var markup = "<textarea name='tcaction[]' id='tcaction' rows='3' cols='105' placeholder='Enter Required Actions' required><?php echo str_replace("<br />", "\n",$text) ?></textarea><br>";

The str_replace within the javascript variable is not working. Would you cordially direct me to the right direction?

Thanks for assistance.

Replace this ...

...<?php echo str_replace("<br />", "\n",$text) ?>...
                                     ^^

... by this:

...<?php echo str_replace("<br />", "\\n",$text) ?>...
                                     ^^^

So PHP sends \\n (2 chars) and JavaScript interprets it as newline character.

All, for the interest of others the issue has been resolved as follows:

var text = <?php echo json_encode($text); ?>

and then used

text.replace("<br />", "\\n");

it works and no issues of un-escaped new line etc etc.

thanks anyway.

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