W3docs

How to Reset File Input with jQuery

In this tutorial, you will read and learn useful information about the fastest method of resetting a file input by using some HTML and jQuery methods.

Resetting a file input is possible and pretty easy with jQuery and HTML. For that purpose, you should wrap a <form> around <input type="file">, then call reset on the form by using the reset() method, then remove the form from the DOM by using the <kbd class="highlighted">unwrap()</kbd> method.

The following jQuery code piece is supported by major browsers and also works on other types of form elements except type="hidden":

Javascript/jQuery reset file input

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  </head>
  <body>
    <div id="file-container">
      <label>File</label><br>
      <input id="fileId" type="file" />
    </div>
    <button id="btn-file-reset-id" type="button">Reset file</button>
    <script>
      $(document).ready(function() {
        $('#btn-file-reset-id').on('click', function() {
          $('#fileId').wrap('<form>').closest('form').get(0).reset();
          $('#fileId').unwrap();
        });
      });
    </script>
  </body>
</html>

If you use a button with type="submit" inside the form, you must call the <kbd class="highlighted">.preventDefault()</kbd> method on the event to prevent the <button> from triggering a form submission.

The reset() method

HTMLFormElement.reset() is a built-in method that is used to reset all form elements to their initial values. It is a simple and efficient way to clear out form data and start over. When the method is called, it resets all input fields, checkboxes, and radio buttons to their default values.

Using HTMLFormElement.reset() is quite simple. All you need to do is call the method on the form element. Here is an example:


const form = document.querySelector('form');
form.reset();