How to clear (reset) the INPUT element value of the file type in JavaScript this article describes how to clear (reset) the INPUT element value of the file type in JavaScript. We will share this with you for your reference. The details are as follows:
Due to security restrictions, the script cannot set its value at will, so it cannot be reset with attributes like other form input fields.
There are three methods to reset the value of a file domain.
This article analyzes the browser compatibility and advantages and disadvantages of these three methods, and provides a perfect comprehensive solution code and Demo.
There are three methods to reset the file domain:
1. Set the value attribute to null.
It is valid for modern browsers such as Chrome/Firefox/Opera... with IE11 and later and other newer Non-IE browsers.
2. Clone or create a new file and replace the input elements.
Use createElement or cloneNode to clone or create a new element to replace it. This applies to all browsers. The disadvantage is that, after replacement, the previously bound event listener will be lost and some custom expando attributes will be lost. It can be used without this problem and is not universal. I do not recommend this method.
3. Call the reset () method of the form element.
The reset () method of the form Element resets all input elements in the form, which is not what we expect. So you can create a new form object as needed, put the input element of the file and reset it again. Then, extract the input element of the file and put it back in the original place. This will not cause the disadvantage of method 2.
By combining method 1 and method 3, you 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); } }}