How to Reset File Input with jQuery

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 unwrap() method.

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

<!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>
    <form>
      <div>
        <label>File</label>
        <br>
        <input id="fileId" type="file">
      </div>
      <div>
        <label>Name</label>
        <br>
        <input id="textId" type="text" value="File name">
      </div>
      <div>
        <button id="btn-file-reset-id" type="button">Reset file</button>
        <button id="btn-text-reset-id" type="button">Reset text</button>
      </div>
    </form>
    <script>
      $(document).ready(function() {
          $('#btn-file-reset-id').on('click', function() {
              $('#fileId').val('');
            });
        });
      $(document).ready(function() {
          $('#btn-text-reset-id').on('click', function() {
              $('#textId').val('');
            });
        });
    </script>
  </body>
</html>

If you have the buttons to trigger the reset of the field inside of the <form> element, you must call the .preventDefault() method on the event to prevent the <button> from triggering a submit.

The reset() method

The HTMLFormElement.reset() method restores the initial values of the form element. This method does the same thing as clicking the reset button.

If a reset button has a name or id of reset it will veil the reset method. It doesn't reset attributes in the input, such as disabled.

Do you find this helpful?

Related articles