Remove selected file from Input type = File in IE

9.4k views Asked by At

How to clear selected file in IE

Following example works in chrome but not in IE (Any version)

http://jsfiddle.net/nfvR9/1/

HTML

<input id="file1" type="file" class="" multiple="" required="" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

Jquery

$("#fileUpload").val('');

As expected IE does not support this.

5

There are 5 answers

0
user2739418 On BEST ANSWER

I end up doing as below:

function reset_form_element(e) {
            e.wrap('<form>').parent('form').trigger('reset');
            e.unwrap();
        }

and then called the function as below:

reset_form_element($('#file1'));
0
Sean Wessell On

I would extend jQuery to have a method to "clearFiles". jQuery depreciated jQuery.browser with 1.9 which is why i am checking if the browser is IE with a variable.

Function Extension:

$.fn.extend({
    clearFiles: function () {
        $(this).each(function () {
            var isIE = (window.navigator.userAgent.indexOf("MSIE ") > 0 || !! navigator.userAgent.match(/Trident.*rv\:11\./));
            if ($(this).prop("type") == 'file') {
                if (isIE == true) {
                    $(this).replaceWith($(this).val('').clone(true));
                } else {
                    $(this).val("");
                }
            }
        });
        return this;
    }
});

Use:

$('#test').click(function () {
    $("[type='file']").clearFiles();
});

Here a fiddle. fiddle

1
Amit.rk3 On

you can have below workaround for IE

$("#image").remove("");
$("form").append(' <input id="image" type="file" name="image"/>');

fiddle- http://jsfiddle.net/nfvR9/25/

0
Luiz Eduardo Simões On

Input filelist is read-only, so you can't remove any files from it, thats why IE doesn't support cleaning the value of the input.

0
Tom aka Sparky On

With much appreciation to Amit.rk3 for his answer, I modified his answer(which I would have put in comments, but I dont have 50 points!!). The OP did say clear a selected file, so I would assume a single input. I have a rather long and complex page, so I wanted to be very specific which input to reset.. The code below works perfect on IE(8) and FF ESR :)

Select Photo(optional): <span id="form_sp"><input id="file" type="file" size="40" name="photo"/></span> <button id="reset_t">Reset file</button>

<script>
$(document).ready(function(){
    $('#reset_t').click(function(e) {
        e.preventDefault(); // keeps form from submitting
        $("#form_sp").html('');
        $("#form_sp").html('<input id="file" type="file" size="40" name="photo"/>');
    });
});
</script>