How To Clear An HTML File Input Field
erics, Posted July 19th, 2012 at 9:59:36am
An HTML file input can’t be cleared by normal means (i.e. setting the value to null or an empty string) because of browser security restrictions. In most browsers, setting a null value attribute either will have no effect or cause an error. Creating a new element that clones the old element and swap the two bypasses this restriction.
A simple example:
1 2 3 4 5 6 |
<form ...> ... <input id="fileInput" name="fileInput" type="file" /> <input onclick="clearFileInput()" type="button" value="Clear" /> ... </form> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function clearFileInput() { var oldInput = document.getElementById("fileInput"); 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); } |
Leave Your Comment
All fields marked with "*" are required.