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
$('#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('');
}) ;

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:

<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").clone(true));

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

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