clear input fields javascript

Clear the Input fields using Javascript

We will often clear the input fields when the form data is submitted or when there is an explicit option to reset the input fields. In this post, we will learn how to clear the input fields when a button is clicked with javascript.  

Clear input fields javascript

In the above video, you can see how all input field data is cleared when the button is clicked.

HTML Code for form

<div class="container">
  <h2>Clearing the Input Fields</h2>
  <form id="userForm">
    <input type="text" value="" placeholder="First Name" id="firstName" />
    <input type="text" value="" placeholder="Last Name" id="lastName" />
    <input type="button" value="Clear All" onclick="clearInput()" />
  </form>
</div>

In the above HTML code we have created a form with 2 input fields of type ‘text’ and the input type ‘button’ which is used as a clear button.

CSS Code

body {
  font-family: "DM Sans", sans-serif;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #495579;
}

.container {
  width: 20rem;
  display: flex;
  flex-direction: column;
  padding: 1.5em;
  gap: 1rem;
  background-color: #fff;
  border-radius: 3px;
}

h2 {
  font-size: 1.1rem;
}

form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  background-color: #fff;
}

input {
  border: none;
  padding: 10px;
  border-radius: 3px;
  background-color: #f6f7f9;
  font-size: 0.8rem;
}

input:focus {
  outline: none;
}

input[type="button"] {
  background-color: #495579;
  color: #fff;
  opacity: 1;
  cursor: pointer;
}

input[type="button"]:active {
  opacity: 0.6;
}

In the above CSS code, we have styled the form, input fields, and button.

Javascript code 

We are using two different ways to clear the input fields using Javascript.

Method 1: By replacing the value with an empty string

const clearInput = () => {
  document.getElementById("firstName").value = "";
  document.getElementById("lastName").value = "";
};

In the above code, we are writing a function that is setting the values of the firstName and lastName input fields to an empty string. We can also clear individual input fields if we need to by setting their value to an empty string. We are calling this function when the user clicks on the clear button.

Method2: Using reset() 

const clearInput = () => {
  document.getElementById("userForm").reset();
};

In this method, we are using the FormElement.reset() method to clear the input fields. When we use this reset() method on the form element, all the input fields in the form will be reset to the default value. This will be very useful when we want to clear all the input field values.

Also, Check this

Leave a Comment

Your email address will not be published. Required fields are marked *