How to Clear Input Fields in Javascript
In this tutorial, you will learn how to clear input fields on button click in javascript. Whenever you create a form whether it’s for login or signup, you must provide your visitor the ability to reset the form, which eventually will clear all input fields.
If you are using the form element, then you can use the reset()
method. It will simply take your form back to its initial state. We are not going to use the form element in this tutorial, but only input elements.
An input element has a value
property that can be used to get and set the value. We can take advantage of this property to clear an input field by setting the value to an empty string.
In the following example, we have 2 input fields and a button element. Upon click of a button, we will clear both the input fields. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,input
, andbutton
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element has“Clear”
asinnerText
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div> <input type="text" placeholder="Enter Username"> <input type="password" placeholder="Enter Password"> <button>Clear</button> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div { display: inline-block; } input, button { display: inline-block; padding: 10px 20px; }
Javascript
- We have selected the
button
element using thedocument.querySelector()
method and stored it in thebtnClear
variable. - We have selected both the
input
elements using thedocument.querySelectorAll()
method and stored it in theinputs
variable. This variable holds an array ofinput
elements. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we are calling
forEach()
method ofinputs
array and in the callback function, we are settingvalue
property to an empty string for eachinput
element.
let btnClear = document.querySelector('button'); let inputs = document.querySelectorAll('input'); btnClear.addEventListener('click', () => { inputs.forEach(input => input.value = ''); });