Borislav Hadzhiev
Tue Jan 04 2022·2 min read
Photo by Amanda Bear
To add text to a textarea, access the value
property on the element and set
it to its current value plus the text to be appended, e.g.
textarea.value += 'Appended text'
. The value property can be used to get and
set the content of a textarea element.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <textarea id="message" rows="5" cols="30"></textarea> <button id="btn">Append text</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const textarea = document.getElementById('message'); // ✅ Append text textarea.value += 'Appended text'; const btn = document.getElementById('btn'); // ✅ Append text on button click btn.addEventListener('click', function handleClick() { textarea.value += 'Appended text'; });
We used the value
property of the textarea element to append text to it.
These two lines achieve the same result.
const textarea = document.getElementById('message'); textarea.value += 'Appended text'; textarea.value = textarea.value + 'Appended text';
Both of them append the text to the end of the current value of the textarea element.
To append text to a textarea element on click:
click
event listener to an element.value
of the textarea
element.const textarea = document.getElementById('message'); const btn = document.getElementById('btn'); // ✅ Append text on button click btn.addEventListener('click', function handleClick() { textarea.value += 'Appended text'; });
The handleClick
function is invoked every time the user clicks the button.
You can also check if the text is already contained in the textarea
, so you
don't add it twice if the user clicks on the button multiple times.
const textarea = document.getElementById('message'); const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { const text = 'Text to append'; if (!textarea.value.includes(text)) { textarea.value += text; } });
We used the includes()
method to check if the text we want to append is
already contained in the value of the text area.
You can also be more specific and check if the value of the textarea ends with the text.
const textarea = document.getElementById('message'); const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { const text = 'Text to append'; if (!textarea.value.endsWith(text)) { textarea.value += text; } });
The endsWith()
method checks if the string the method was called on ends with
the provided string.