To get the value from an input field, we can use the jQuery val method. We can also use the val() method to set the value of an input field.
var userInput = $("input").val();
Let’s say we have the following HTML:
To get the value that the user has entered for “Full Name”, we would use the jQuery val() method.
$("#fname").val();
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#fname").val();
This can also be done using plain JavaScript with the value property.
Get and Set an Input Field using the jQuery val() Method
In this example, we will have a form that will display the information of a user. We will then let the user update one of the fields by using an input field and submit button below it.
Here is the HTML setup:
Update
In the JavaScript code below, we will get the user input using the jQuery val() method, and then set the input value “Username” in the form above using the val() method as well.
Here is the JavaScript code for getting and setting an input field:
$("#click-me").click(function(){
var userInput = $("#new-username").val();
$("#username").val(userInput);
});
The final code and output for this example of getting and setting an input field using the jQuery val() method is below:
Code Output:
Full Code:
Update
<script>
$("#click-me").click(function(){
var userInput = $("#new-username").val();
$("#username").val(userInput);
});
</script>
Hopefully this article has been useful to help you understand how to use the jQuery val method to get the value from an input field.