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?
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) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With