Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set text in <textarea>, including newlines

I want to set the text in a <textarea> from a js-function; I'm simply setting the innerText-attribute to a new value. The text is multiline and should be displayed as such. However, newlines are dropped by the browser and the entire text is displayed as one line:

document.getElementById("my_textarea1").innerText = "foo\nbar"; // displayed as "foobar"

document.getElementById("my_textarea2").innerText = "foo\
    bar"; // displayed as "foobar"

document.getElementById("my_textarea3").innerText = `foo\
    bar`; // again, "foobar"
<textarea id="my_textarea1"></textarea>
<textarea id="my_textarea2"></textarea>
<textarea id="my_textarea3"></textarea>

Is there a way to preserve newlines when setting the text in a <textarea>?

like image 397
user2722968 Avatar asked Aug 11 '18 11:08

user2722968


2 Answers

Try it. I use property "value" or "innerHTML" or "textContent":

var area = document.getElementById("my_textarea");
area.value = "foo\nbar";

var area_2 = document.getElementById("my_textarea_2");
area_2.innerHTML = "foo\nbar";

var area_3 = document.getElementById("my_textarea_3");
area_3.textContent = "foo\nbar";
<textarea id="my_textarea"></textarea>
<textarea id="my_textarea_2"></textarea>
<textarea id="my_textarea_3"></textarea>
like image 113
Ly Thanh Ngo Avatar answered Sep 24 '22 03:09

Ly Thanh Ngo


You can set the value of the textarea, this works with \n, and

`foo\
bar`;

document.querySelector("#my_textarea").value = "foo\nbar"
<textarea id="my_textarea"></textarea>

If that doesn't work for you, use the innerHTML property, the same way:

document.querySelector("#my_textarea").innerHTML = "foo\nbar"
<textarea id="my_textarea"></textarea>
like image 25
Luca Kiebel Avatar answered Sep 22 '22 03:09

Luca Kiebel