How to Clear the Input Field Value using JavaScript
Table of Contents
JavaScript is an important tool to use in making forms more interactive and user-friendly.
It allows you to do things like validation, error messages, and clearing form fields.
In this post, we'll learn how you can use JavaScript to clear the value of an input field.
Clearing Input Field Value
Clearing the input field value is useful when you want to reset a form, or to clear a form after a user submits it.
Let's start with a basic example form:
HTML<form>
<input type="text" name="username" placeholder="Username" class="username" />
<button class="clear">Clear</button>
</form>
In this small form, we have an input field with a name of username
, and a button with a class of clear
.
When the user clicks the button, we want to clear the value of the input field.
To accomplish this, we first must query for both elements, which we can use querySelector
for:
JAVASCRIPTconst username = document.querySelector(".username");
const clear = document.querySelector(".clear");
Then, we can add an event listener to the button. Inside the event listener, we can use the value
property to clear the input field:
JAVASCRIPTconst username = document.querySelector(".username");
const clear = document.querySelector(".clear");
clear.addEventListener("click", () => {
username.value = "";
});
Now, when you click the button, the input field will be cleared.
Conclusion
In this post, we learned how to clear the value of an input field. As mentioned before, this is most common when you want to reset a form after submitting it.
Hopefully, you learned something and found this useful.
Happy coding!
- Getting Started with Svelte
- Getting Started with Express
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js