How can I clear an HTML file input with JavaScript?
Asked Answered
S

22

321

I want to clear the file input in my form.

I know about setting the sources to the same method... But that method wont erase the selected file path.

Note: I would like to avoid having to reload the page, reset the form or perform an AJAX call.

Is this possible?

Safelight answered 9/11, 2009 at 19:34 Comment(0)
G
332

There's 3 ways to clear file input with javascript:

  1. set value property to empty or null.

Works for IE11+ and other modern browsers.

  1. Create an new file input element and replace the old one.

    The disadvantage is you will lose event listeners and expando properties.

  2. Reset the owner form via form.reset() method.

To avoid affecting other input elements in the same owner form, we can create an new empty form and append the file input element to this new form and reset it. This way works for all browsers.

I wrote a javascript function. demo: http://jsbin.com/muhipoye/1/

function clearInputFile(f){
    if(f.value){
        try{
            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
        }catch(err){ }
        if(f.value){ //for IE5 ~ IE10
            var form = document.createElement('form'),
                parentNode = f.parentNode, ref = f.nextSibling;
            form.appendChild(f);
            form.reset();
            parentNode.insertBefore(f,ref);
        }
    }
}
Gunman answered 7/7, 2014 at 10:5 Comment(3)
Should not we also remove created form afterwards?Liebfraumilch
No, you need not. the form element has not been appended to the page document tree.Gunman
Just a word of warning, using approaches 2. or 3. might have implications for you if you want to preserve events and other attributes that were added to an element programmatically. In my case, I added an onclick event to a form element which disappeared after form reset. In such a case, approach 1. is better. (This was noted for 2., but can also happen for 3.)Telescopic
C
199

tl;dr: For modern browsers, just use

input.value = '' or input.value = null;


Old answer:

How about:

input.type = "text";
input.type = "file";

I still have to understand why this does not work with webkit.

Anyway, this works with IE9>, Firefox and Opera.
The situation with webkit is that I seem to be unable to change it back to file.
With IE8, the situation is that it throws a security exception.

Edit: For webkit, Opera and firefox this works, though:

input.value = '';

(check the above answer with this proposal)

I'll see if I can find a nice cleaner way of doing this cross-browser without the need of the GC.

Edit2:

try{
    inputs[i].value = '';
    if(inputs[i].value){
        inputs[i].type = "text";
        inputs[i].type = "file";
    }
}catch(e){}

Works with most browsers. Does not work with IE < 9, that's all.
Tested on firefox 20, chrome 24, opera 12, IE7, IE8, IE9, and IE10.

Chassepot answered 25/4, 2013 at 19:12 Comment(0)
W
73

Setting the value to '' does not work in all browsers.

Instead try setting the value to null like so:

document.getElementById('your_input_id').value= null;

EDIT: I get the very valid security reasons for not allowing JS to set the file input, however it does seem reasonable to provide a simple mechanism for clearing already selecting output. I tried using an empty string but it did not work in all browsers, NULL worked in all the browsers I tried (Opera, Chrome, FF, IE11+ and Safari).

EDIT: Please note that setting to NULL works on all browsers while setting to an empty string did not.

Wilkie answered 16/1, 2014 at 7:33 Comment(2)
Unfortunately I'm not seeing this in all browsers... it doesn't work in IE8, IE9 or IE10 (but does work in IE11).Terminal
Well dang. I didn't test older versions of the IE browser. Sorry.Wilkie
T
42

Unfortunately none of the above answers appear to cover all the bases - at least not with my testing with vanilla javascript.

  • .value = null appears to work on FireFox, Chome, Opera and IE11 (but not IE8/9/10)

  • .cloneNode (and .clone() in jQuery) on FireFox appears to copy the .value over, therefore making the clone pointless.

So here is the vanilla javascript function I have written that works on FireFox (27 and 28), Chrome (33), IE (8, 9, 10, 11), Opera (17)... these are the only browsers currently available to me to test with.

function clearFileInput(ctrl) {
  try {
    ctrl.value = null;
  } catch(ex) { }
  if (ctrl.value) {
    ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
  }
}

The ctrl parameter is the file input itself, so the function would be called as...

clearFileInput(document.getElementById("myFileInput"));
Terminal answered 19/3, 2014 at 12:36 Comment(10)
This is the answer. One of the problems with so many answers to this question--not just on this page, but searching other forums, as well, is that you can clear the "3 files selected" text, but it doesn't actually clear the http files queue. What happens then is that the next time you try to upload, you can only select one file, and worse, it gets saved to the previous file folder. This answer will clear both, and you can resume uploading the next set of files just as easily as you uploaded the first set of files.Centerboard
Shouldn't the if statement be placed inside the catch block?Bodily
@Bodily - no, it shouldn'tTerminal
Oh I thought that IE8/9/10 will throw an exception when trying to set the value to null. Mind to explain what's the point of putting ctrl.value = null; inside a try...catch block then? Sorry for the newb question.Bodily
@Bodily - you've just given the answer... it will throw an exception. If, after running ctrl.value = null it still has a value, then it will run the clone/replace. If the if statement was in the try, then it wouldn't be reached if an exception took place on the ctrl.value = nullTerminal
LOL I totally forgot that any code following a try...catch will get executed as normal. That's why I got confused just now. Ah silly me.Bodily
ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl); - at what point actually we clear the value, since cloneNode also copies it?Bodily
Why didn't you use a finally block here? It is more clear instead of an empty catch block IMHOCakewalk
@Arda - because I wrote it over 6 years ago, and probably wasn't aware of finally at the time. Unless you know different, there should be absolutely no difference in outcome, so I see no need to change my answerTerminal
@Terminal no there is no different in the outcome. After seeing people asking whether the if block should be inside the try or catch block I thought using finally results in a clearer code. However it is just personal taste. I just wondered if there is a reason :) good reply anyway, thanks!Cakewalk
C
18

SOLUTION

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

var $el = $('#your-input-id');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();

DEMO

See this jsFiddle for code and demonstration.

LINKS

Clockwork answered 31/7, 2015 at 17:42 Comment(0)
M
16
document.getElementById('your_input_id').value=''

Edit:
This one doesn't work in IE and opera, but seems to work for firefox, safari and chrome.

Merritt answered 9/11, 2009 at 19:36 Comment(2)
This works for me, although I always ask myself for how long.Lewanna
this wont work, just in some browsers, and also setting the value of a file input is a security breach... not good choice.Safelight
E
11

U need replace it with new file input. Here is how it can be done with jQuery:

var inputFile = $('input[type=field]');
inputFile.wrap('<div />');

and use this line when you need to clear input field (on some event for example):

inputFile.parent().html( inputFile.parent().html() );
Extroversion answered 21/7, 2011 at 22:50 Comment(2)
For replace the original element, this looks better: #1044457Aldous
This works in 2022Minatory
I
11

Here are my two cents, the input files are stored as array so here is how to null it

document.getElementById('selector').value = []

this return an empty array and works on all browsers

Ilowell answered 27/4, 2020 at 19:49 Comment(0)
K
9

the input.value = null is a working method, however it will only trigger input's change event if called from an onclick event.

Solution to that would be calling that onchange handler manually whenever you need to reset the input.

function reset_input(input) {
    $(input)[0].value = null;
    input_change_handler();
}
function input_change_handler() {
    // this happens when there's been a change in file selection

    if ($(input)[0].files.length) {
        // file(s) selected
    } else {
        // nothing is selected
    }
}
$(input).on('change', input_change_handler);

Klystron answered 27/7, 2020 at 20:42 Comment(1)
Isn't a file type read only - so file.value=null would not work.Mimosa
R
7

That's actually quite easy.

document.querySelector('#input-field').value = '';
Rhinoscopy answered 25/2, 2019 at 11:55 Comment(0)
C
5

I was having same problem and i came up with this.

var file = document.querySelector('input');
var emptyFile = document.createElement('input');
emptyFile.type = 'file';

document.querySelector('button').onclick = function(){
  file.files = emptyFile.files;
}
<input type='file'>
<button>clear</button>
Cryptogenic answered 29/10, 2018 at 17:52 Comment(0)
M
5

This worked for me.

const clear = (event) =>{event.target.value = [ ];}
clear("input_id"); 
Marlin answered 14/8, 2020 at 17:22 Comment(2)
Uncaught SyntaxError: Unexpected identifierRodneyrodolfo
Lambda unreadable solutions. Bravo!Genoese
S
5

An - in my world easy an clean solution - is, to set the file inputs files to a clear FileList.

EDIT: as SteJ told - this ist not working with Safari.

Since we can not create a FileList directly - I user DataTransfer as "hack"

@$input[0].files=new DataTransfer().files 

or

file_input_node.files=new DataTransfer().files 
Sexdecillion answered 12/2, 2021 at 0:22 Comment(3)
This won't currently work with Safari; Safari does not allow you to create a new instance of DataTransfer.Unavailing
@SteJ: :( - because of the Apple politics, I have no Safari to test :( - THX, I Write this as Edit.Sexdecillion
No issue with new DataTransfer() in IOS 15.4 safariThievery
L
4

I have been looking for simple and clean way to clear HTML file input, the above answers are great, but none of them really answers what i'm looking for, until i came across on the web with simple an elegant way to do it :

var $input = $("#control");

$input.replaceWith($input.val('').clone(true));

all the credit goes to Chris Coyier.

// Referneces
var control = $("#control"),
    clearBn = $("#clear");

// Setup the clear functionality
clearBn.on("click", function(){
    control.replaceWith( control.val('').clone( true ) );
});

// Some bound handlers to preserve when cloning
control.on({
    change: function(){ console.log( "Changed" ) },
     focus: function(){ console.log(  "Focus"  ) }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" id="control">
<br><br>
<a href="#" id="clear">Clear</a>
Litchi answered 13/12, 2017 at 14:21 Comment(1)
..and to you buddy, this helped me when checking and displaying errors in a potential file upload. This resets on error and lets the user re-upload the same file in case anyone is looking for something like this.Egad
G
3

Try this easy and it works

let input = elem.querySelector('input[type="file"]');
input.outerHTML=input.outerHTML;

this will reset the input

Godfather answered 22/1, 2021 at 15:2 Comment(0)
R
2

Simplest way is to set event.target.value to null.

<input accept="image/jpeg, image/png"
      id="logo-file"
      type="file"
      onChange={handleLogoChange}/>

const handleLogoChange = (event: any) => {
       const logoFile = event.target.files[0];
       if (logoFile!.size > 10000) {
          // 👇️ reset file input
           event.target.value = null;

          // 👇️ is now empty
          console.log(event.target.files);
       }
 };
Rotenone answered 25/10, 2023 at 11:8 Comment(0)
S
1

The above answers offer somewhat clumsy solutions for the following reasons:

  1. I don't like having to wrap the input first and then getting the html, it is very involved and dirty.

  2. Cross browser JS is handy and it seems that in this case there are too many unknowns to reliably use type switching (which, again, is a bit dirty) and setting value to ''

So I offer you my jQuery based solution:

$('#myinput').replaceWith($('#myinput').clone())

It does what it says, it replaces the input with a clone of itself. The clone won't have the file selected.

Advantages:

  1. Simple and understandable code
  2. No clumsy wrapping or type switching
  3. Cross browser compatibility (correct me if I am wrong here)

Result: Happy programmer

Swifter answered 2/3, 2014 at 20:33 Comment(4)
Cross browser compatibility... my testing shows that FireFox copies over the .value as part of the .clone(), therefore rendering it uselessTerminal
@Terminal why not change the value before calling replaceWith? I am using clone() myself and it's working fine in firefox (I don't know if this is still the case for you a year later =) )Expostulate
@Expostulate - if you look at my answer you'll see that I doTerminal
The question isn't asking about jQuery; it's asking about javascript.Hobie
G
1

I changed to type text and back to type to file using setAttribute

'<input file-model="thefilePic" style="width:95%;" type="file" name="file" id="filepicture" accept="image/jpeg" />'

'var input=document.querySelector('#filepicture');'

if(input != null)
{
    input.setAttribute("type", "text");
    input.setAttribute("type", "file");
}
Gramnegative answered 3/7, 2020 at 13:0 Comment(0)
A
1
  1. Make the value null or empty string like this `` in order to clear value of a single input element

  2. You can easily reset all form values using the HTML button using the <input type=”reset”> attribute.

  3. The HTMLFormElement.reset() method restores a form element's default values. This method does the same thing as clicking the form's control.

To clear the entire input field without having to delete the whole thing manually Or what if there is already a pre-suggested input present in the input field, that the user doesn’t want. There could be many scenarios.

You can try this as a live example

const fileInputElement = document.getElementById('file-input');
const formElement = document.getElementById('input-form');


// Method-1: Clear files
// fileInputElement.value = '';

// Method-2: Clear files
// fileInputElement.value = null;

// Method-3: Clear files - on event listener
fileInputElement.addEventListener('change', (event)=>{
  // If the file did not meet certain condition
  event.target.value = '';
});


  // Method-4: Clear or reset whole form
formElement.addEventListener('submit', (event)=>{
  // If ajax call is failed to make request
  event.target.reset();
  // or 
  // formElement.reset()
});
.form{
  display: flex;
  flex-direction: column;
  width: 80%;
  margin-left: 10%;
}

#file-input, .form-control{
  margin-top: 1rem;
}

.form-control{
  padding: 1em 0;
}

#file-input{
  background: #ccccff;
}

#file-input::-webkit-file-upload-button {
  background: #000033;
  color: white;
  padding: 1em;
}
.button-group{
  display: flex;
  justify-content: start;
}

.btn{
  background: #004d4d;
  color: white;
  width: 4rem !important;
  margin-right: 10px;
}
<form id='input-form' class='form' >
  <input type='file' id='file-input' />
  <input type='text' class='form-control'  id='text-input' placeholder='your name' />
  <div class='button-group'>
  <button type='reset' class='form-control btn' id='reset-form'>Reset</button>
  <button type='submit' class='form-control btn' id='submit-form'>Submit</button>
  </div>
</form>
Aggregation answered 29/10, 2022 at 6:25 Comment(0)
D
1

Simplest way on a modern browser:

const elemFile = document.getElementById('file_id');
elemFile.value = null;
elemFile.dispatchEvent(new Event('change'))

The event dispatching is the important bit, as the file element will ony pick up the null value on change.

Dexterdexterity answered 3/8, 2023 at 22:47 Comment(0)
O
0

What helped me is, I tried to fetch and upload the last selected file using a loop, instead of clearing out the queue, and it worked. Here is the code.

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

Hope this might help some.

Oceanid answered 22/3, 2018 at 16:40 Comment(0)
B
-1

I tried most of solutions but did not seem anyone to work. However I found a walk around for it below.

The structure of the form is: form => label, input and submit button. After we choose a file, the filename will be shown by the label by doing so manually in JavaScript.

So my strategy is: initially the submit button is disabled, after a file is chosen, the submit button disabled attribute will be removed such that I can submit file. After I submit, I clear the label which makes it look like I clear the file input but actually not. Then I will disable the submit button again to prevent from submitting the form.

By setting the submit button disable or not, I stop the file from submitted many times unless I choose another file.

Bui answered 8/12, 2018 at 5:56 Comment(1)
This doen't answer the OP's question.Or

© 2022 - 2024 — McMap. All rights reserved.