Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a carriage return when using jQuery append with textarea text

I have text that comes from a textarea where the user might have legitimate carriage returns.

If the text has a carriage return that I want to preserve, how do I do that with this exact jQuery append example.

I'm generating this html code and it will break if the variable $text has carriage returns in it.

Example:

$(".inner").append( "<textarea><?php echo $text; ?></textarea>" );

So if:

$text = "Cat

Dog";

Then I get this and it causes an error.

$( ".inner" ).append( "<textarea>Cat

Dog</textarea>" );

What can I do to preserve the carriage returns when append creates this textarea html?

like image 797
Chain Avatar asked Aug 04 '15 19:08

Chain


1 Answers

You need to make sure that the php value gets passed to javascript correctly. The best way to do that, is to encode it as json. Then you can use for example .val() to set the value of your element:

var myText = <?php echo json_encode($text); ?>;
$( ".inner" ).append( $('<textarea>').val(myText) );
like image 128
jeroen Avatar answered Oct 07 '22 00:10

jeroen