We can clear an input field using jQuery easily by making use of the jQuery val() method. We simply need to set the value of the input field to an empty string.
$(input).val("");
Let’s see a quick example of this below:
Let’s say we have the following HTML:
The input field in the example above will have the text “This is some default text.”. If we want to clear the input field in the example above, we would use the following jQuery code:
$("#userText").val("");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#userText").val("");
Let’s do an interactive example of clearing an input field below.
Using jQuery to Clear an Input Field with a Click
Below we will have a simple input field. It will start prefilled with a random name to start, “Joe Smith”. We will then let the user clear the input.
Here is our simple HTML:
Clear input field above
We will simply use the jQuery val() method to set the input field to an empty string. We will use the jQuery click() method when the user clicks the button below the input field to call our val() method.
Here is the jQuery code:
$("#click-me").click(function(){
$("#userText").val("");
});
The final code and output for this example of how to clear an input field using jQuery is below:
Code Output:
Full Code:
Clear input field above
Note we can also do this using just plain JavaScript by targeting the value property.
Getting the Value From an Input Field Using jQuery
To get the value from an input field using jQuery, we can once again use the jQuery val() method.
Let’s say we have the following HTML:
To get the value that the user has entered for “Full Name”, we would use the val() method.
var userInput = $("#fname").val();
Hopefully this article has been useful to help you understand how to clear an input field using jQuery.