The example in this article describes the method of clearing (resetting) the file type INPUT element value in JavaScript. Share it with everyone for your reference, the details are as follows:
Due to security restrictions, the script cannot set its value arbitrarily, so it cannot be reset using attributes like other form input fields.
To reset the value of a file field, there are three main methods.
This article analyzes the browser compatibility, advantages and disadvantages of these three methods, and gives the code and demo of a relatively perfect comprehensive solution.
Three ways to reset the file domain:
1. Set the value attribute to empty.
Effective for IE11 or above and other newer non-IE modern browsers Chrome/Firefox/Opera....
2. Clone or create a new file input element to replace.
Use createElement or cloneNode to clone or create a new element for replacement, suitable for all browsers. The disadvantage is also obvious, that is, after replacement, the originally bound event listener will be lost, and some custom expando attributes will be lost. It can be used without this problem, but it is not universal. I do not recommend using this method.
3. Call the reset() method of the form element.
The reset() method of the form element will reset all input elements in the form. This is not what we expect, so we can work around it, create a new form object, put the file input element into it, reset it, and then Take out the file input element and put it back in place, so that the disadvantages of method 2 will not occur.
Using method 1 and method 3 combined, it can be compatible with all browsers.
The JavaScript function code is as follows:
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); } } }