Get the Value of Text Input Field using JavaScript (original) (raw)
Last Updated : 09 Jan, 2025
**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 or
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 , . 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 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. HTML `
<!-- 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>
`
**Output:
Getting the Value of a Textarea
**Example : Here, we are getting the text area value using value property.
- A
- A button with an onclick event handler is provided to trigger the getValue() function.
- The getValue() function retrieves the
<!-- 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>
`
**Output: