I have a file type input button that I am needing to clear completely if the user chooses to and the only safe solution I have found is to completely destroy the input and rebuild it. What I have right now works but it is a "Harp Gun" solution in that it only works once.
Basically, the user has a file input like so:
<input type="file" name="filesToUpload" id="filesToUpload" onChange="makeFileList();" />
<ul id="fileList"><li>No Files Selected</li></ul>
And when they select a file, they may need to clear that completely.
So I have this being built up via appending it on to the filelist:
function makeFileList() {
var input = document.getElementById("filesToUpload");
var ul = document.getElementById("fileList");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < input.files.length; i++) {
var li = document.createElement("li");
var fileSize = input.files[i].size;
li.innerHTML = input.files[i].name +" "+ "<span id=\"lblSize\"></span><input onclick=\"clearFileInput()\" type=\"button\" value=\"Clear\" \/>";
ul.appendChild(li);
}
if(!ul.hasChildNodes()) {
var li = document.createElement("li");
li.innerHTML = 'No Files Selected';
ul.appendChild(li);
}
};
And to completely destroy the file, the function rebuilds the input like so:
function clearFileInput(){
var oldInput = document.getElementById("filesToUpload");
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;
// copy any other relevant attributes
oldInput.parentNode.replaceChild(newInput, oldInput);
};
So I can create the element, add the file type, and use the old input ID, class and name. But I need it to have the same onChange="makeFileList(); behavior as well.
Here is a FIDDLE. Any help is appreciated.