How to use Value Property to get value In Javascript
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.
Using Value Property to get value Example:
Here, we are using the Value property to get the value of the text input field.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Input Value Example</ 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:
Explanation:
Here,
- An
<input>
element with the ID"myInput"
is defined. - A button with an
onclick
event handler is provided to trigger thegetValue()
function. - The
getValue()
function retrieves the input element usinggetElementById()
, accesses itsvalue
property to get the text entered by the user, and displays it in an alert.
Using Value Property to get value Example:
Here, we are getting the text area value using value property.
HTML
<!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:
Explanation:
Here,
- A
<textarea>
element with the ID"myTextarea"
is defined. - A button with an
onclick
event handler is provided to trigger thegetValue()
function. - The
getValue()
function retrieves the<textarea>
element usinggetElementById()
, accesses itsvalue
property to get the text entered by the user, and displays it in an alert.
Get the value of text input field using JavaScript
To get the value of a text input field using JavaScript, you can use the DOM Input Text value Property
of the input element.
Syntax for getting the value of text
inputField.value;
Syntax for setting the value of text
inputField.value = text;
Contact Us