Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML posting removes line breaks

Tags:

html

textarea

I have a really simple html / php code. It has only a textarea and a send button.

In the textarea, i have a text what has 3 new lines at the begining of the text. I need those line breaks.

After, when i submitting the form, for some reason, it is chop 1 of the line break at the begining of the text. And when i send it again, it do it again, remove line breaks, while the begining of the content is not a text.

Why is it happening? I tried it with FF, Chrome, Safari, Oprea, IE with the same result.

You can test it with this code:

<?php
if (empty($_POST["operation"])) {
    //Init the textarea value if form not submitted
    $_POST["message"] = "\r\n\r\n\r\nThis is\r\na multiline text";
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Multiline test</title>
    <meta charset="UTF-8" />
</head>
<body>
    <form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
    <textarea style="width: 200px; height: 150px;" name="message"><?php echo $_POST["message"]; ?></textarea>
    <input type="submit" value="send" />
    <input type="hidden" name="operation" value="send" />
    </form>
</body>

like image 792
vaso123 Avatar asked Nov 02 '22 21:11

vaso123


1 Answers

Browsers ignore the first and last line breaks inside the <textarea> tag. This is because if you wouldn't want any extra line breaks if you write the HTML like this:

<textarea>
Textarea content, all in one line.
</textarea>

The simple solution in this case is to just add one line break before printing the textarea contents.

<textarea style="width: 200px; height: 150px;" name="message">
<?php echo $_POST["message"]; ?>
</textarea>

Also note that you don't need \r\n. Just \n is enough.

like image 183
JJJ Avatar answered Nov 09 '22 11:11

JJJ