Search code examples
phphtmltextareanewlineline-breaks

Textarea ignoring multiple line breaks at beginning


I have a form that populates itself from a database. I have checked all the data being retrieved and am confident it is correct.

One of my fields returns text with two line breaks at the beginning of it. When I echo the text, it shows these two line breaks, however, if I echo the text in a textarea, it ignores one of the line breaks...

Consider this:

$data['field'] = "\n\nTest";

// This shows two line breaks in the code
echo $data['field'];

// This shows two line breaks in the code, but only displays one in the textarea
echo '<textarea>'.$data['field'].'</textarea>'

Is this because the following are the same:

<textarea>
    Value Here
</textarea>

<textarea>Value Here</textarea>

If so, how can I get around this? Should I just add a line break to any data that starts with a line break?


Solution

  • I had almost the same problem and wasn't able to reproduce it first but later I figured out the reason: after minifying the HTML, every textarea will be displayed in one line. There seems to be a difference.

    <textarea>Value here</textarea>
    
    • You should consider the difference between raw and minified HTML.

    • If you're using an WYSIWYG-Editor (e.g. TinyMCE), try it without.

    If nothing helps, I'd add a line-break at the beginning - as you already mentioned. Feels a little dirty, unfortunately.