Before StackOverflow answered this question, now organize into a blog.
Due to security restrictions. The script cannot set its value values arbitrarily, so it cannot be set to reset with the properties as other form input fields.
Resetting the value of a file field is summed up in 3 ways.
This article analyzes the browser compatibility and pros and cons of these three methods, and gives a perfect comprehensive solution code and demo.
Three ways to reset a file domain:
- Set the Value property to null.
For IE11 above and other newer non-IE modern browser chrome/firefox/opera ... Effective.
- Clone or create a new file INPUT element to replace.
Replace with createelement or CloneNode clones or create a new element for all browsers. The disadvantage is also obvious, that is, after the substitution, the previously bound event listener is lost, and some of the expando properties you define are lost. It is not possible to use the case without this problem. Not universal. I don't recommend using this method.
- invokes the Reset () method of the form form element.
The reset () method of the form element resets all input elements in the form, which is not expected. So it's possible to work around creating a new Form object. Put the file INPUT element into the reset, and then the file INPUT element out to put back in place, so that there is no disadvantage of Method 2.
Combined with Method 1 and Method 3, all browsers can be compatible.
JavaScript function code such as the following:
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 '), ref = f.nextsibling, p = f.parentnode; Form.appendchild (f); Form.reset (); P.insertbefore (F,REF);}}}
View demo:http://jsbin.com/muhipoye/1/
Empty (reset) The value of the INPUT element of the file type with JavaScript