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>
?
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>
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>
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