<textarea> and line breaks

I'm doing HTML since the very late 1990s. The <textarea> element was introduced with HTML 2.0 in November 1995. That means, the <textarea> was there some years before me. I added textareas to my websites and applications uncountable times. And I also as a user, I used forms with textarea for a quarter of a century without batting an eye. - Until I wanted to show a string inside a <textarea> that started with a line break.

Different possible notations #

In the years without regret, I did not really care if I did the notation with line breaks or without line breaks. All the following examples showed up in my code.

<textarea>Single Line</textarea>
<textarea>
Single Line
</textarea>
<textarea>Line 1
Line 2
Line 3</textarea>
<textarea>
Line 1
Line 2
Line 3
</textarea>

Or I even mixed them up in several combinations. I'm sure you can imagine further possible notations.

Why does it matter #

Some time ago, I was in the situation that in one of my projects, I had a textarea, where it should be possible to explicitly add some lines with text and keep other ones empty, e.g.:



line 3
line 4


line 7


When I submitted the editor form with this data and the form reloaded with the database content, I realized that the first line break was gone:


line 3
line 4


line 7


Tests #

I did some tests to find out, what browsers are doing

No line breaks at all #

<textarea>Foo</textarea>

That's an easy one - we all know what will happen:

Single line break before and after the content #

<textarea>
Foo
</textarea>

On first sight, it may look the same as above. But if you look closer, you realize you can move the cursor to the line after "Foo"

Two line break before and after the content #

<textarea>

Foo

</textarea>

If you do the cursor test, you will realize there is one line break before the text but two line breaks after the text.

Learnings #

There are two learnings from my observations:

1. The first line break directly after the opening tag <textarea> is ignored. #

<textarea>
Foo

and

<textarea>Foo

are exactly the same.

2. The line break directly before the closing tag </textarea> is respected. #

Foo</textarea>

and

Foo
</textarea>

are two different strings.

Conclusion #

Since I know that, I only can recommend to add your values in a single way:

In pseudo code, your textareas should look like this:

<textarea>
$value</textarea>

Looks weird, feels weird. But it solved my problems.