556

I am developing a metro app with VS2012 and Javascript

I want to reset the contents of my file input:

<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />

How should I do that?

9

28 Answers 28

535

The jQuery solution that @dhaval-marthak posted in the comments obviously works, but if you look at the actual jQuery call it's pretty easy to see what jQuery is doing, just setting the value attribute to an empty string. So in "pure" JavaScript it would be:

document.getElementById("uploadCaptureInputFile").value = "";
9
  • 19
    Thanks! If you already have the jquery reference anyway, $input.val("") will work as usual.
    – Natan
    Commented Mar 1, 2014 at 13:57
  • @2ndGAB Hmm... I only have 45.0.1 so I can't test... anyone else? Commented May 5, 2016 at 19:08
  • @2ndGAB Correction, My Firefox just updated to 46.0.1 and this code still works there. Can you confirm? Commented May 5, 2016 at 19:09
  • @jakerella that's strange, for me, set an input file selector value trigs a Security exception. The only solution I successfully use is $(#myfileselector).trigger('fileselect', [1, ""]);
    – fralbo
    Commented May 9, 2016 at 7:48
  • 7
    input.type = ''; input.type = 'file'; //enjoy Commented Feb 2, 2017 at 11:59
98

You need to wrap <input type = “file”> in to <form> tags and then you can reset input by resetting your form:

onClick="this.form.reset()"
3
  • 7
    This is the correct method. It works in all browsers and does not conflict with any protections that browsers implement to prevent rogue scripts from messing around with file input's .value. Commented Mar 21, 2016 at 8:26
  • 21
    Kinda cool, not for me though, cause it also resets other fields on this form.
    – Starwave
    Commented Dec 5, 2017 at 9:54
  • 2
    A similar jQuery solution could be $("form").get(0).reset();. The .get(0) will return the actual form element so you can use the reset() function.
    – teewuane
    Commented Mar 16, 2018 at 16:16
90

This is the BEST solution:

input.value = ''

if(!/safari/i.test(navigator.userAgent)){
  input.type = ''
  input.type = 'file'
}

Of all the answers here this is the fastest solution. No input clone, no form reset!

I checked it in all browsers (it even has IE8 support).

6
  • 8
    Is there any specific reason to reset the input.type too? Setting just the value to '' is giving the expected result. Commented Mar 3, 2017 at 13:05
  • 1
    This needs some more upvotes or something, I took far too long to find this answer, this is the only one I found that works on IE.
    – sch
    Commented Jan 4, 2018 at 12:27
  • 1
    input.value = '' throws an exception to the console in IE11. However resetting input.type works on all browsers without any error. Commented Nov 15, 2018 at 7:08
  • This answer is not good enough. If the input is set as required, resetting the field should make the field invalid again. Unfortunately in this case, it is still valid, so the form will submit, although with no value.
    – pepkin88
    Commented Apr 24, 2019 at 16:50
  • I would set value to null, but basically same thing.
    – CodeFinity
    Commented May 26, 2019 at 22:38
67

In case you have the following:

<input type="file" id="fileControl">

then just do:

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

to reset the file control.

4
  • 7
    Best solution IMHO. Commented Mar 17, 2017 at 18:33
  • 8
    Or use DOM: inputFileEl.value = '';
    – ninhjs.dev
    Commented May 22, 2017 at 4:29
  • is using "val" in javascript source code cause some security issues?
    – nima
    Commented Jul 23, 2021 at 12:32
  • @novonimo No, since all it does is set the value of an input. And if someone wanted to, they could just use their browser's DevTools to run JavaScript. Commented Jul 23, 2021 at 15:22
56

Another solution (without selecting HTML DOM elements )

If you added 'change' event listener on that input, then in javascript code you can call (for some specified conditions):

event.target.value = '';

For example in HTML:

<input type="file" onChange="onChangeFunction(event)">

And in javascript:

onChangeFunction(event) {
  let fileList = event.target.files;
  let file = fileList[0];
  let extension = file.name.match(/(?<=\.)\w+$/g)[0].toLowerCase(); // assuming that this file has any extension

  if (extension === 'jpg') {
    alert('Good file extension!');
  }
  else {
    event.target.value = '';
    alert('Wrong file extension! File input is cleared.');
  }
4
  • Another way to angular2: stackoverflow.com/questions/40165271/…
    – Belter
    Commented Nov 23, 2017 at 7:37
  • This will only work on filenames which contain just a single . in front of file extension.
    – Ma Kobi
    Commented Dec 19, 2017 at 8:13
  • That's right, I have edited the code and provided more universal approach to get a file extension.
    – indreed
    Commented Jan 24, 2018 at 15:28
  • This is the only solution that allows the change event to re-fire if the user subsequently selects the same file.
    – ianjoneill
    Commented Nov 24, 2022 at 16:38
45

You can just clone it and replace it with itself, with all events still attached:

<input type="file" id="control">

and

var input = $("#control");

function something_happens() {
    input.replaceWith(input.val('').clone(true));
};

Thanks : Css-tricks.com

6
  • 1
    Unfortunately this doesn't reset input value, see this jsFiddle. For a better solution, see this answer. Commented Jul 31, 2015 at 17:40
  • 1
    @Gyrocode.com This jsFiddle doesn't work if the image is uploaded second time after reset. Commented Aug 7, 2015 at 9:40
  • 2
    @SarthakSinghal, Unfortunately you wrote the wrong code, you should have done jsfiddle.net/cL1LooLe Commented Sep 14, 2015 at 23:08
  • 2
    @RogerRussel: Exactly... I was wondering myself how come upper answers were saying that it only works once which is a clear indicator that some sort of reference is being lost. And that was actually the case because the initially created the input reference that was later replaced with a new input element. Commented Oct 23, 2015 at 21:10
  • 1
    Just resetting the value like in other answers seems much more straightforward than manipulating the DOM.
    – CodeFinity
    Commented May 26, 2019 at 22:39
43
document.getElementById('uploadFile').value = "";

Will work, But if you use Angular It will say "Property 'value' does not exist on type 'HTMLElement'.any"

document.getElementById() returns the type HTMLElement which does not contain a value property. So, cast it into HTMLInputElement

(<HTMLInputElement>document.getElementById('uploadFile')).value = "";

EXTRA :-

However, we should not use DOM manipulation (document.xyz()) in angular.

To do that angular has provided @ViewChild, @ViewChildren, etc which are document.querySelector(), document.queryselectorAll() respectively.

Even I haven't read it. Better to follows expert's blogs

Go through this link1, link2

5
  • 3
    glad I don't have to use angular! Commented Nov 5, 2019 at 4:07
  • No. FIx would be there. Only I found this one. Which you are using then? Commented Nov 5, 2019 at 5:51
  • Sorry, I was being sarcastic...I just use document.getElementById('uploadFile').value = ""; as I don't use angular. Commented Nov 6, 2019 at 0:31
  • Nice one. I thought the same, But, use Angular/ React/ VUe. These are powerful frameworks for routing, component, service, dom manipulation override implemenration Commented Nov 6, 2019 at 2:01
  • This doesnt work in Anguar 13!! Nothing works. Setting the value to '' doesnt work. Setting the file list of new DataTransfer().files doesnt work. Nothing works! Commented Jan 25, 2022 at 18:33
34

SOLUTION

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

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

DEMO

See this jsFiddle for code and demonstration.

LINKS

See How to reset file input with JavaScript for more information.

2
  • 1
    @alessadro, no, just element <input type="file"> with specific ID. Commented Jan 2, 2017 at 1:03
  • 1
    This is the cleanest and most browser-compliant solution I have found yet - thank you.
    – Pat
    Commented Apr 14, 2017 at 16:59
28

Resetting a file upload button is so easy using pure JavaScript!

There are few ways to do it, but the must straightforward way which is working well in many browser is changing the filed value to nothing, that way the upload filed gets reset, also try to use pure javascript rather than any framework, I created the code below, just check it out (ES6):

function resetFile() {
  const file = document.querySelector('.file');
  file.value = '';
}
<input type="file" class="file" />
<button onclick="resetFile()">Reset file</button>

2
  • how to do with jquery Commented May 14, 2018 at 7:11
  • 1
    @AnandChoudhary this works inside jQuery as well, but you can replace const file = document.querySelector('.file'); with const file = $('.file'); or just do $('.file').val(""); to empty it
    – Alireza
    Commented May 14, 2018 at 7:30
18

I miss an other Solution here (2021): I use FileList to interact with file input.

Since there is no way to create a FileList object, I use DataTransfer, that brings clean FilleList with it.

I reset it with:

  file_input.files=new DataTransfer().files  

In my case this perfectly fits, since I interact only via FileList with my encapsulated file input element.

17

I use for vuejs

   <input
          type="file"
          ref="fileref"
          @change="onChange"/>

this.$refs.fileref.value = ''
2
  • 3
    Thanks man! I thought I will never find a solution with vuejs :D, you mad my day!
    – Zsoca
    Commented Mar 16, 2019 at 14:15
  • 1
    Worked like a charm! Thank you
    – F KIng
    Commented Jan 27, 2020 at 4:54
11

The reseting input file is on very single

$('input[type=file]').val(null);

If you bind reset the file in change other field of the form, or load form with ajax.

This example is applicable

selector for example is $('input[type=text]') or any element of the form

event click, change, or any event

$('body').delegate('event', 'selector', function(){
     $('input[type=file]').val(null) ;
});
1
  • Or you can use $('input[type=file]').val('') ; also
    – w.Daya
    Commented Apr 26, 2022 at 5:54
10

My Best Solution

$(".file_uplaod_input").val('');  // this is working best ):
1
  • 1
    How is this different from the first answer and the comments on that answer? Commented Nov 18, 2019 at 16:24
9

There are many approaches and i will suggest to go with ref attachment to input.

<input
    id="image"
    type="file"
    required
    ref={ref => this.fileInput = ref}
    multiple
    onChange={this.onFileChangeHandler}
/>

to clear value after submit.

this.fileInput.value = "";
6

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"/>
6

Just use:

$('input[type=file]').val('');
0
6

document.getElementById("uploadCaptureInputFile").value = "";

5

With angular you can create a template variable and set the value to null

<input type="file" #fileUploader />
<button (click)="fileUploader.value = null">Reset from UI</button>

Or you can create a method to reset like this

component.ts

  @ViewChild('fileUploader') fileUploader:ElementRef;

  resetFileUploader() { 
    this.fileUploader.nativeElement.value = null;
  }

template

<input type="file"/>
<button (click)="resetFileUploader()">Reset from Component</button>

stackblitz demo

5
<input type="file" id="mfile" name="mfile">
<p>Reset</p>

<script>
$(document).ready(function(){
$("p").click(function(){

            $("#mfile").val('');
            return false;

    });
});

2
  • 2
    While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review Commented Mar 31, 2020 at 9:50
  • $("#mfile").val('') will empty the file input field.
    – w.Daya
    Commented Jan 14, 2021 at 8:47
3

You can´t reset that since it is an read-only file. you can clone it to workaround the problem.

3

You should try this:

$("#uploadCaptureInputFile").val('');
3

I faced the issue with ng2-file-upload for angular. if you are looking for the solution in angular refer below code

HTML:

<input type="file" name="myfile" #activeFrameinputFile ng2FileSelect [uploader]="frameUploader" (change)="frameUploader.uploadAll()" />

component

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

@ViewChild('activeFrameinputFile')InputFrameVariable: ElementRef;

this.frameUploader.onSuccessItem = (item, response, status, headers) => {

`this.`**InputFrameVariable**`.nativeElement.value = '';`

};

3

This could be done like this

var inputfile= $('#uploadCaptureInputFile')
$('#reset').on('click',function(){
inputfile.replaceWith(inputfile.val('').clone(true));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />
<a href="" id="reset">Reset</a>

2

jQuery solution:

    $('input').on('change',function(){
                $(this).get(0).value = '';
                $(this).get(0).type = '';
                $(this).get(0).type = 'file';
            });
3
  • Consider padding this answer out to explain how it works.
    – Bugs
    Commented Feb 3, 2017 at 13:11
  • @Bugs guess this speaks for itself. When the file input's on change event is triggered the value gets cleared. The type of the input gets resetted from none to file.
    – user443346
    Commented Feb 13, 2017 at 8:49
  • 2
    @Jordy yes I know what it does :) I was just thinking that with a dozen other answers it would be worth trying to make it stand out. It appeared whilst I was reviewing. They could in fact copy your comment to pad it out that bit more. It's always worth trying to explain why you feel the code fixes the OPs problem.
    – Bugs
    Commented Feb 13, 2017 at 9:02
0

If you have several files in your form but only want one of them to be reset:

if you use boostrap, jquery, filestyle to display the input file form :

$("#"+idInput).filestyle('clear');
0
var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));
0

Works for dynamic controls too.

Javascript

<input type="file" onchange="FileValidate(this)" />

function FileValidate(object) {
    if ((object.files[0].size / 1024 / 1024) > 1) {   //greater than 1 MB         
        $(object).val('');
    }     
}

JQuery

<input type="file" class="UpoloadFileSize">

$(document).ready(function () {

    $('.UpoloadFileSize').bind('change', function () {                
        if ((this.files[0].size / 1024000) > 1.5) { //greater than 1.5 MB
            $(this).val('');
            alert('Size exceeded !!');
        }
    });

});
0

function resetImageField() {
    var $el = $('#uploadCaptureInputFile');                                        
    $el.wrap('<form>').closest('form').get(0).reset();
    $el.unwrap();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />
<button onclick="resetImageField()">Reset field</button>

Not the answer you're looking for? Browse other questions tagged or ask your own question.