1

I have a website that has a form. In the form I have a textarea field. When this is filled and displayed in the manner below

eg . this is how it was written in the textarea box

The manager,

Abc limited,

private bag,

earth.

It displayed like this

The manager, Abc limited, private bag, earth.

how can I make it stay the way it was written

RaphaMex
  • 2,781
  • 1
  • 14
  • 30
Arnav Nath
  • 71
  • 2
  • 3
  • 12

6 Answers6

1

You can use the innerText attribute of the element that will hold the textarea value.

Important: At the backend side, you have to preserve the \n in the Database or whatever it's being used to store the data to get it back and render the content exactly as was saved.

var div = document.querySelector('div');
var textarea = document.querySelector('textarea');

div.innerText = textarea.value;
textarea.addEventListener('input', function() {
  div.innerText = this.value;
});
<h3>Enter text and press enter</h3>
<small>The entered text will appear automatically</small>
<p>
<textarea>
The manager,

Abc limited,

private bag,

earth.</textarea>
<div></div>
Ele
  • 33,468
  • 7
  • 37
  • 75
1

The only way I was able to recreate your error was by misspelling <textarea> as <text area>. When the space is added, the error occurs. When properly spelled line breaks are preserved.

showdev
  • 28,454
  • 37
  • 55
  • 73
saltchicken
  • 170
  • 9
1

HTML ignores new lines/whitespace unless you style the element with white-space:pre like in this example

Lee Kowalkowski
  • 11,591
  • 3
  • 40
  • 46
  • I have tried using `.replace(/\n\r?/g, '
    ');`. Only works when assigning value to `InerHTML` element in Javascript. But not works for `fetch` value to backend. The special character code will returns. (`<br />>`). So your approach works fine for me.
    – parmer_110 Mar 26 '23 at 03:54
0

You will have to use \n for line breaks inside textarea

Sletheren
  • 2,435
  • 11
  • 25
0

If you are using php, then you can echo echo nl2br($textarea);

https://www.w3schools.com/php/func_string_nl2br.asp

or for jquery

jQuery convert line breaks to br (nl2br equivalent)

jvk
  • 2,133
  • 3
  • 19
  • 28
0

Well you are not really giving us a lot to go on how you print the text field. But my guess is that if you use php you should wrap your variable in a nl2br() function.

Get more information here: http://php.net/manual/en/function.nl2br.php

Rasmus Stougaard
  • 433
  • 2
  • 11