Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save user-entered line breaks from a TextArea to a database?

Tags:

html

People also ask

How do you preserve line breaks in a div?

The easiest solution is to simply style the element you're inserting the text into with the following CSS property: white-space: pre-wrap; This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea> .

How do you preserve a new line in HTML?

The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.

What is textarea form element used for How does the user enter data?

The HTML textarea tag is used to make a text input field with multiple lines in a form. It is defined with the <textarea> tag and can hold an unlimited number of characters.


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>

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


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.


I know from experience that Browser text areas are less well-behaved than one would like, especially with regard to line breaks.

You could can to see if javascript would be able to interrogate the text area and find the line breaks before the text is sent to the server and so send the data in a more well-formatted way. But the amount of javascript debugging necessary to make this work across multiple browsers is probably not worth the effort.

Perhaps you should say that format you are trying to capture your data. There may be a better way to get the data than keeping track of line-breaks - though lines breaks can seem like any easy thing to capture in user input.