How to add line breaks to an HTML textarea?
If you use general JavaScript and you need to assign a string to a text area value, then document.getElementById("textareaid").value='texthere\\ntexttext'.
You need to replace \n
or < br >
with \\\n
.
Otherwise, it gives Uncaught SyntaxError: Unexpected token ILLEGAL in all browsers.
The 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 />');
Since many of the comments and my own experience have shown 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';
}