Reputation: 81
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
Upvotes: 1
Views: 2062
Reputation: 33726
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>
Upvotes: 1
Reputation: 11751
HTML ignores new lines/whitespace unless you style the element with white-space:pre
like in this example
Upvotes: 1
Reputation: 170
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.
Upvotes: 1
Reputation: 433
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
Upvotes: 0
Reputation: 2211
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)
Upvotes: 0