16

how can I reset file input in IE, I used the following and it worked in chrome and FF but not IE

fileInputElement.value=""

what's the alternative in IE ?

Sami Al-Subhi
  • 4,406
  • 9
  • 39
  • 66

5 Answers5

18

If fileInputElement is on its own in the form fileInputForm, you can do:

window.fileInputForm.reset();

Otherwise for IE you'll have to replace the element with a clone:

fileInputElement.parentNode.replaceChild(
    fileInputElement.cloneNode(true), 
    fileInputElement
);
mVChr
  • 49,587
  • 11
  • 107
  • 104
7

SOLUTION

The following code worked for me with jQuery. It works in every browser and allows to preserve events and custom properties.

var $el = $(fileInputElement);
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();

DEMO

See this jsFiddle for code and demonstration.

LINKS

Community
  • 1
  • 1
Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
  • Thank you so much! I've tried many solutions on SO. Most don't work. Here's the one that works. -- and in just 3 lines. <3 – Sparky1 Jan 11 '18 at 23:13
5

Cross-Browser solution by @Gyrocode.com in vanilla JS:

var clearFileInput = function (input) {
  if (!input) {
    return;
  }

  // standard way - works for IE 11+, Chrome, Firefox, webkit Opera
  input.value = null;

  if (input.files && input.files.length && input.parentNode) {
    // workaround for IE 10 and lower, pre-webkit Opera

    var form = document.createElement('form');
    input.parentNode.insertBefore(form, input);

    form.appendChild(input);
    form.reset();

    form.parentNode.insertBefore(input, form);
    input.parentNode.removeChild(form);
  }

}
Frank Adler
  • 131
  • 1
  • 8
4

You can't reset the File input by itself. What you can do is wrap your File input in a <form id="form_id"> tag and reset the form. With jQuery you can do $('#form_id')[0].reset(); and in JavaScript you can do document.getElementById('form_id').reset().

Gavin
  • 7,544
  • 4
  • 52
  • 72
  • Any idea why document.getElementById('form_id').reset() works, document.getElementById('form_id')[0].reset() doesnt, and why jquery requires the [0]? (thanks by the way, you saved me atleast 30 minutes) – Ulad Kasach Nov 07 '14 at 04:01
  • 1
    `getElementById()` doesn't return an array, so there is no index `[0]` in the result. jQuery does return an array of objects, so when you specify `[0]` you are retrieving the first element in the returned set. – Gavin Nov 07 '14 at 04:48
0

With IE 10 I resolved the problem with :

    var file = document.getElementById("file-input");
    file.removeAttribute('value');
    file.parentNode.replaceChild(file.cloneNode(true),file);

where :

<input accept="image/*" onchange="angular.element(this).scope().uploadFile(this)" id="file-input" type="file"/>
Alvaro Silvino
  • 9,441
  • 12
  • 52
  • 80