How do I save user-entered line breaks from a HTML element to a database?
It always removes the line breaks.
When displaying the content you need to convert line breaks into <br />
tags, otherwise the web browser won't display them. This is probably why you think they aren't being saved. If you're using PHP, use the nl2br() function to do this. In other languages you could do a string replace, replacing all occurrences of "\n"
with "<br />"
.
Pure CSS solution, NOT php specific
In normal cases, the TextArea
HTML element is preserving the white space in the database.
The problem appears when trying to display the \n
on the web browser, which will fail.
To display \n
in the web browser use :
<p style="white-space: pre-line">multi-line text</p>
I noticed that breakable content saved normally if textarea is inside a html form. But if I use textarea without any form and try to edit a long text in it, insert line breaks and save content via ajax, it's saved as a merged text into database
This will help.
<textarea></textarea>
instead of a input
<input type="text">
The database will keep this.
Just put the output text between <pre></pre>
tags, that will preserve the line breaks.
I just learnt to use php's nl2br function and it is working fine for me. I'm using it to style how my users receive an email when sent from another user.