Get the Value of Text Input Field using JavaScript
Last Updated :
09 Jan, 2025
Improve
Getting the value of a text input field using JavaScript refers to accessing the current content entered by a user in an input element, such as <input> or <textarea>, by utilizing the value property. This allows for dynamic interaction and data manipulation in web forms.
Syntax
inputField.value;
inputField.value = text;
Getting the Value of a Text Input Field
The value property in JavaScript represents the current value of an input element, such as <input>, <textarea>, or <select>. It allows you to access and manipulate the text, number, or selected option within the input element.
Example: Here, we are using the Value property to get the value of the text input field.
- An <input> element with the ID “myInput” is defined.
- A button with an onclick event handler is provided to trigger the getValue() function.
- The getValue() function retrieves the input element using getElementById(), accesses its value property to get the text entered by the user, and displays it in an alert.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Using Value Property</title>
</head>
<body>
<!-- Input field -->
<input type="text" id="myInput" placeholder="Enter text">
<!-- Button to get input value -->
<button onclick="getValue()">Get Value</button>
<!-- Script to get input value -->
<script>
function getValue() {
// Get the input element by its ID
let inputField = document.getElementById("myInput");
// Get the value of the input field
let value = inputField.value;
// Display the value in an alert
alert("Input value: " + value);
}
</script>
</body>
</html>
Output:
Getting the Value of a Textarea
Example : Here, we are getting the text area value using value property.
- A <textarea> element with the ID “myTextarea” is defined.
- A button with an onclick event handler is provided to trigger the getValue() function.
- The getValue() function retrieves the <textarea> element using getElementById(), accesses its value property to get the text entered by the user, and displays it in an alert.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Textarea Value Example</title>
</head>
<body>
<!-- Textarea -->
<textarea id="myTextarea"
rows="4" cols="50"
placeholder="Enter text"></textarea>
<!-- Button to get textarea value -->
<button onclick="getValue()">Get Value</button>
<!-- Script to get textarea value -->
<script>
function getValue() {
// Get the textarea element by its ID
let textarea = document.getElementById("myTextarea");
// Get the value of the textarea
let value = textarea.value;
// Display the value in an alert
alert("Textarea value: " + value);
}
</script>
</body>
</html>
Output: