When a user submits a form on a website that doesn’t refresh the page or redirects the user to a success page, you often want to clear the form fields. Here’s how to do that with vanilla JavaScript.
1. HTML: a login form
Here’s a typical HTML login form where the user types in their username and password, before hitting the Login (submit) button:
<form>
<label for="username">Username:</label>
<input type="text" id="username" />
<label for="password">Password:</label>
<input type="password" id="password" />
<button>Login</button>
</form>
2. JavaScript: clear form fields on submit
This code will clear every field in the form as soon as the user hits submit:
// Run function when a submit event is registered
document.addEventListener("submit", function(event) {
// Prevent default form submit
event.preventDefault()
// Clear all form fields
event.target.reset()
})