How to reset file input with jQuery

Problem

You need to reset file input element (<input type="file">) in a complex form without affecting other elements.

Solution

  • Wrap a new <form> element around <input type="file"> element using wrap() method
  • Reset newly added <form> element with our file upload control using reset() method
  • Remove newly added <form> element from the DOM using unwrap() method

The benefit of this method is that it preserves the original <input type="file"> element and therefore allows to retain existing event handlers attached to it.

Demo



$('#btn-example-file-reset').on('click', function(e){
   var $el = $('#example-file');
   $el.wrap('<form>').closest('form').get(0).reset();
   $el.unwrap();
});

Edit on jsFiddle

Related posts

Leave a Reply

You may use simple HTML to add links or lists to your comment. Also use <pre><code class="language-*">...</code></pre> to mark up code snippets. We support language-js, language-markup and language-css for comments.
(Optional)