Append text to Textarea using JavaScript

avatar

Borislav Hadzhiev

Tue Jan 04 20222 min read

banner

Photo by Amanda Bear

Append text to Textarea using JavaScript #

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.

index.html
<!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.

index.js
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.

index.js
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:

  1. Add a click event listener to an element.
  2. Each time the element is clicked, update the value of the textarea element.
index.js
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.

index.js
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.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee