I’m editing a <textarea>
with JavaScript. The problem is that when I make line breaks in it, they won’t display. How can I do this?
I’m getting the value to write a function, but it won’t give line breaks.
To add a line break to your HTML code, you use the <br> tag. The <br> tag does not have an end tag. You can also add additional lines between paragraphs by using the <br> tags.
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.
Use block-level elements to break the line without using <br> tag. There are many ways to break the line without using <br> tag. The used properties are listed below: white-space: pre; It is used to make elements acts like <pre> tag.
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
Problem comes from the fact that line breaks (\n\r
?) are not the same as HTML <br/>
tags
var text = document.forms[0].txt.value; text = text.replace(/\r?\n/g, '<br />');
UPDATE
Since many of the comments and my own experience have show me that this <br>
solution is not working as expected here is an example of how to append a new line to a textarea
using '\r\n'
function log(text) { var txtArea ; txtArea = document.getElementById("txtDebug") ; txtArea.value += text + '\r\n'; }
I decided to do this an edit, and not as a new question because this a far too popular answer to be wrong or incomplete.
if you use general java script and you need to assign string to text area value then
document.getElementById("textareaid").value='texthere\\\ntexttext'.
you need to replace \n
or < br >
to \\\n
otherwise it gives Uncaught SyntaxError: Unexpected token ILLEGAL
on all browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With