We can clear an input field using JavaScript easily by making use of the value property. We simply need to set the value of the input field to an empty string.
document.getElementById("input1").value = "";
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 JavaScript code:
document.getElementById("userText").value = ""
Let’s do an interactive example of clearing an input field below.
Using JavaScript 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:
We will simply use the value property to set the input field to an empty string. We will need to put this code in a function that we call when the user clicks the button below the input field.
We will add an onclick event to our button below the input field that will call our function.
Here is the JavaScript function:
function clearInput(){
document.getElementById("userText").value = "";
};
The final code and output for this example of how to clear an input field using JavaScript is below:
Code Output:
Full Code:
Getting the Value From an Input Field Using JavaScript
To get the value from an input field, we can once again use the value property.
Let’s say we have the following HTML:
To get the value that the user has entered for “Full Name”, we would use the value property.
document.getElementById("fname").value;
This can also be done using jQuery with the val() method.
Hopefully this article has been useful to help you understand how to clear an input field in JavaScript.