4

I've modified my current form to trigger a form submission after a user chooses a file for upload. After the upload is complete I call:

$('#file').val('');

to reset the file input field.

HTML
<input name="file" type="file" id="file"/>

This works on Chrome, FF, and Safari but doesn't work in IE. Is there a workaround or a better solution for IE?

Paul
  • 11,671
  • 32
  • 91
  • 143
  • Here's a duplicate for this: [Clearing using jQuery](http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery) – jabclab Dec 03 '11 at 13:59
  • @jabclab so wat ?? that ques. dsnt have any accepted answer... and this quest gave me the solution. – Ashish Ratan Jun 24 '14 at 06:10

1 Answers1

7

You can't change the value of a file input type, as that would introduce a security vulnerability. Instead, just replace the file input with a new one. Instead of $('#file').val(''), do this:

$('#file').replaceWith('<input name="file" type="file" id="file"/>');

Even better would be to clone a copy of the original version and store it in memory. When you need to replace it, just used the cloned copy, and again clone it. So, something like this:

$(document).ready(function() {
    var empty_input = $('#file').clone();

    $('#the-form').on('change', '#file', function(el) {
        $('#the-form').submit(); // assuming the target is a hidden iframe
        $(this).replaceWith(empty_input.clone());
    });
})

Note that I'm using the delegated version with jQuery.on() so the event will still work on the new input right after it's replaced.

Ben Lee
  • 52,489
  • 13
  • 125
  • 145