How to clear the form after submitting in Javascript without using reset

The form allows us to take input from users and manipulate it at the front end or backend side of the application. Also, to provide a good user experience to the application user, we need to reset all the form data once the user submits the form.

Example: 

In the example below, we have created multiple input forms of different types. After that, in JavaScript, we used the querySelector() method to select all inputs. In the forEach() loop, we have passed the callback function, which sets the empty string for a value attribute of each input.

When the user clicks the ‘submit’ button, it clears all input fields.


<!DOCTYPE html> 
<html>
<body style="background-color:powderblue;">
   <h2 style="color:red">Clearing only all input fields of form when a user submits the form</h2>
   <form>
      First Name: <input type = "text" id = "input1" />
      <br> <br>
      Last Name: <input type = "text" id = "input2" />
      <br> <br>
      Email: <input type = "email" id = "input3" />
      <br> <br>
   </form>
   <button type = "submit" onclick = "submit()"> Submit </button>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById('output');
      function submit(event) {
         var allInputs = document.querySelectorAll('input');
         allInputs.forEach(singleInput => singleInput.value = '');
         output.innerHTML += "Form submitted and cleared successfully! <br>";
      }
   </script>
</body>
</html>

Leave a comment

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