Chris Burgess Chris Burgess - 4 years ago 87
HTML Question

clearing an HTML file upload field via JS

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

is this possible via JS? i'm suspecting that the file upload element is treated differently b/c it interacts with the user's FS, and maybe it's immutable

basically, what i want is something like (pseudo)

// choose selecting existing file
$('#select-file').bind('focus', function() {
// clear any files currently selected in #upload-file
}) ;

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

Answer Source

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:

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

The straight DOM way:

function clearFileInput(id) 
    var oldInput = document.getElementById(id); 

    var newInput = document.createElement("input"); 

    newInput.type = "file"; =; =; 
    newInput.className = oldInput.className; =; 
    // TODO: copy any other relevant attributes 

    oldInput.parentNode.replaceChild(newInput, oldInput); 


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:


Resetting the whole form via jQuery:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download