[javascript] how to reset <input type = "file">

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?

This question is related to javascript visual-studio-2012 winjs

The answer is


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


Particularly for Angular

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


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


In case you have the following:

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

then just do:

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

to reset the file control.


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 = "";

My Best Solution

$(".file_uplaod_input").val('');  // this is working best ):

Just use:

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

This could be done like this

_x000D_
_x000D_
var inputfile= $('#uploadCaptureInputFile')_x000D_
$('#reset').on('click',function(){_x000D_
inputfile.replaceWith(inputfile.val('').clone(true));_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />_x000D_
<a href="" id="reset">Reset</a>
_x000D_
_x000D_
_x000D_


var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));

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

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

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

    });
});


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.


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.


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 = '';`

};


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


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


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.');
  }

You should try this:

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

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).


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 = "";

jQuery solution:

    $('input').on('change',function(){
                $(this).get(0).value = '';
                $(this).get(0).type = '';
                $(this).get(0).type = 'file';
            });

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) ;
});

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


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()"

I use for vuejs

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

this.$refs.fileref.value = ''

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

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):

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


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 !!');
        }
    });

});

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');