How to add a value to a textarea in HTML?
When dealing with forms and user inputs, a
texarea is likely to come up in one way or another. They give the user an ability to write enter a sizeable amount of text in one field.
This is frequently used for inputs such as:
Sometimes we need to manually add a value to the
texarea. This is typically required when we need a default value to be shown. So, how can you add value to a textarea in HTML? To add a value into a textarea, you can add to the value property of the input via document.getElementById.
This is demonstrated by the following example:
Reference this element and change the value:
document.getElementById("comment-text").value += 'Test Feedback';
While this will change the value dynamically, what if we want to change the default value?
Well, the best method for inserting a default value for
textareais to insert text between the
<textarea id="comment-text">Test text</textarea>
This allows the user to click the field and continue typing with that value inside it.
This differs from using the
placeholder attribute, where the text is never actually editable by the user.
<textarea placeholder="Test text" id="comment-text"></textarea>
In this case, the text will be grayed out and once the field is clicked, it will be replaced with an empty text field.
And there you have it. Remember, leaving a text area without default or placeholder text is uninviting for the user to click into. Make sure that your text areas use one of these methods.