This article explains how to obtain and set the values of text boxes and text areas included in HTML forms using JavaScript.
Please tell me how to get and set the value of a text box/text area!
This section explains how to obtain and set the values of text boxes and text areas included in HTML forms.
How to get the value of a textbox or textarea
The method to obtain the values of text boxes and text areas in HTML forms is achieved by using the Document Object Model (DOM).
DOM allows you to manipulate elements within an HTML document.
To get and set the value of a text box, follow these steps:
- Assign IDs to HTML text boxes and text areas.
- Use ” document.getElementById ” method in JavaScript to get text box, text area .
- Use the value property of the retrieved text box to retrieve and set the value of the text box and text area.
Sample to get and set text box value
The sample below gets and sets the value of a text box.
<input type="text" id="textbox">
<button onclick="getValue()">acquisition</button>
<button onclick="setValue()">setting</button>
function getValue() {
var textbox = document.getElementById("textbox");
alert(textbox.value);
}
function setValue() {
var textbox = document.getElementById("textbox");
textbox.value = "New Value";
}
In the sample above, a text box and two buttons are placed in the HTML. When you click the “Get” button, the value in the text box will be displayed in an alert. Click the “Set” button to set the value in the text box to “New Value”.
Sample for getting and setting text area values
The sample below gets and sets the value of the text area.
<textarea id="textarea"></textarea>
<button onclick="getValue()">acquisition</button>
<button onclick="setValue()">setting</button>
function getValue() {
var textarea = document.getElementById("textarea");
alert(textarea.value);
}
function setValue() {
var textarea = document.getElementById("textarea");
textarea.value = "New Value";
}
In the sample above, a text box and two buttons are placed in the HTML. When you click the “Get” button, the value in the text box will be displayed in an alert. Click the “Set” button to set the value in the text box to “New Value”.
Summary of this article
We explained how to obtain and set the values of text boxes and text areas included in HTML forms using JavaScript.
- Use document.getElementById method to get the value of text box and text area.
- Use the value property to set the value.
Now you understand how to get and set the value of a text box.
Comments