We can get the value of the text input field using various methods in JavaScript. There is a text value property that can set and return the value of the value attribute of a text field. Also, we can use the jquery val() method inside the script to get or set the value of the text input field.
The below are the 2 different approaches for getting or setting the value of the text input field:
Using text value property: The text value property is used to set or return the value of a value attribute of the input field. The value attribute specifies the initial value of the Input Text Field. It contains the default value or the user types.
Syntax:
Get value : textObject.value
Set value : textObject.value = text
Example 1: This example uses the Text value property to get the value from the input text field.
HTML
<!DOCTYPE html>
< html >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksforGeeks
</ h1 >
< h2 >Text value property</ h2 >
< p >
Change the text of the text field,
and then click the button below.
</ p >
Name:< input type = "text" id = "myText" value = "Mickey" >
< button type = "button" onclick = "myFunction()" >Try it</ button >
< p id = "demo" ></ p >
< script >
// Here the value is stored in new variable x
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</ script >
</ body >
</ html >
|
Output:

Text value Property
Using jquery val() method: The val() method is used to return or set the value attribute of the selected elements. In default mode, this method returns the value of the value attribute of the FIRST matched element & sets the value of the value attribute for ALL matched elements.
Syntax:
Get value : $(selector).val()
Set value : $(selector).val(value)
Example 2: This example describes the jquery val() method to fetch the values from the input field.
HTML
<!DOCTYPE html>
< html >
< head >
< script src =
</ script >
< script >
$(document).ready(function() {
$("button").click(function() {
// Here the value is stored in variable.
var x = $("input:text").val();
document.getElementById("demo").innerHTML = x;
});
});
</ script >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksforGeeks
</ h1 >
< h2 >jquery val() method</ h2 >
< p >
Change the text of the text field, and
then click the button below.
</ p >
< p >Name:< input type = "text" name = "user"
value = "GeeksforGeeks" >
</ p >
< button >Get the value of the input field</ button >
< p id = "demo" ></ p >
</ body >
</ html >
|
Output:

jQuery val() Method