There's 3 ways to clear file input with javascript:
set value property to empty or null.
Works for IE11+ and other modern browsers.
Create an new file input element and replace the old one.
The disadvantage is you will lose event listeners and expando properties.
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);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…