Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing an HTML file upload field via JavaScript

I want to reset a file upload field when the user selects another option.

Is this possible via JavaScript? I'm suspecting that the file upload element is treated differently because it interacts with the user's file system, and maybe it's immutable.

Basically, what I want is something like (pseudo-code):

// Choose selecting existing file $('#select-file').bind('focus', function() {   // Clear any files currently selected in #upload-file   $('#upload-file').val('');  }) ;  // Choose uploading new one - this works ok $('#upload-file').bind('focus', function() {   // Clear any files currently selected in #select-file   $('#select-file').val('');  }) ; 

NB: This question and its answers span the period from 2009 to today. Browsers and approaches have changed in that time, please select your solutions with this in mind :)

like image 690
Chris Burgess Avatar asked May 06 '09 13:05

Chris Burgess


People also ask

How do you clear the input field in HTML?

To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.

How do I clear input field after submit?

In the event handler, we just set input. value to an empty string. Then when we select a file for the input and click clear, we see that the selected file is gone. We can also set value to null to do the same thing.

How do you clear out a field?

In the table design grid, select the field that you want to delete, and then press DEL.


1 Answers

You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.

Given a form like:

<form>      <input id="fileInput" name="fileInput" type="file" />  </form> 

The straight DOM way:

function clearFileInput(id)  {      var oldInput = document.getElementById(id);       var newInput = document.createElement("input");       newInput.type = "file";      newInput.id = oldInput.id;      newInput.name = oldInput.name;      newInput.className = oldInput.className;      newInput.style.cssText = oldInput.style.cssText;      // TODO: copy any other relevant attributes       oldInput.parentNode.replaceChild(newInput, oldInput);  }  clearFileInput("fileInput"); 

Simple DOM way. This may not work in older browsers that don't like file inputs:

oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput); 

The jQuery way:

$("#fileInput").replaceWith($("#fileInput").val('').clone(true));  // .val('') required for FF compatibility as per @nmit026 

Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947

like image 97
Chris Hynes Avatar answered Oct 23 '22 05:10

Chris Hynes