Anonymous Anonymous - 1 month ago 9
HTML Question

how to add text to textarea w/ javascript but still be able to type in it afterwards?

I am trying to add text to a textarea in javascript, but, before you mark this as a duplicate, it doesn't allow me to add more text inside the textarea after I've typed anything else in there.



var f1t = true;

var foo = function() {
if (f1t === true) {
document.getElementById("textarea").innerHTML += "<i:>"
f1t = false
} else {
document.getElementById("textarea").innerHTML += "<:>"
f1t = true
}
}

<textarea id="textarea"></textarea> <button onclick="foo();">+</button>





When this code is ran, it will put as many things inside the textarea as I want until I type something. Then, when the function is called, it wont put anything in the textarea and wont throw any errors. I want to be able to continuously add text to the textarea even after I've typed something.

Answer

The innerHTML of a textarea describes it's default value and not its current value. Once the user types something, it's default value is irrelevant (unless you have a reset button).

Set the value property instead.

Comments