| by Arround The Web | No comments

How to Use textarea Input in JavaScript

In HTML, the element <textarea> defines a multi-line text input control. The “cols” and “rows” attributes define the dimensions of a text area. It is frequently used in a form to gather user inputs such as reviews or comments. To get the textarea input in JavaScript, you have to use the “getElementById(‘id’)” method with the “value” attribute.

This post will describe the method to use the input of the textarea in JavaScript.

How to Use Textarea Input in JavaScript?

For using the textarea input in JavaScript, you have to perform two main operations:

  • Get the entered textarea input value
  • Set the new value in the textarea

Example
In an HTML file, first, create a textarea and assign a value “Linuxhint”:

<textarea id="txtArea" name="txtArea" rows="5" cols="55">Linuxhint</textarea><br><br>

Create two buttons “Get the Text” and “Add new Text”, that will call the functions “getText()” and “setText()”, respectively, on the button’s click event:

<button id="get" onclick="getText()">Get the Text</button>
<button id="set" onclick="setText()">Add new Text</button>

After executing the above HTML code, the page will look like as follows:

Now, in the JavaScript file, define a function “getText()” that will trigger on the click event. Here, we will get the input value using the “getElementById()” method and show it in the “alert()” method:

function getText() {
 var text = document.getElementById("txtArea").value;
 alert(text);
}

Define a function “setText()” that will trigger on the “Add new Text” button and set the specified text in the text area:

function setText() {
 var text = document.getElementById("txtArea").value = “Linuxhint is the best Website for Learning Skills”;
}

The output shows that the pre-entered value of the textarea is displayed in the alert message by clicking the “Get the Text” button. Then, we set the new input value in the text area using the “Add new Text” button. Lastly, the input textarea value is fetched using the “Get the Text” button:

That’s all about using textarea input in JavaScript.

Conclusion

To use the textarea input in JavaScript, you have to get the input values or set the input value to the textarea. For getting the textarea input, use the “getElementById(‘id’)” method with the “value” attribute and for setting the input value, use the “getElementById(‘id’).value = ‘text’”. This post described the method to use the input of the textarea in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply