Clearing a File Input Field Using JQuery
While working on some file uploads today, I was in need to a way to clear a file input field if a user changed their mind after selecting a file. I came up with the following simple solution.
In my example I place a ‘clear’ link next to the field, but a modified method could be called from anywhere.
HTML
Wrap the field you intend to clear in a span, with a descriptive ID so we can find it.
We’ll also want our ‘clear’ link to be descriptively IDed.
clear
JavaScript
Now in our JavaScript (JQuery) we want to add a click event to our clear link which will clear the file input field.
$('#clearmyfile').click(function(){
var fieldSpan = $('#myfileinput');
fieldSpan.html(fieldSpan.html());
});
Explanation
Since we can’t write to the value of a file input field due to security concerns, instead we overwrite the contents of the span, with the contents of the span (itself), thus creating a new file input DOM object which doesn’t have a value set.
A crude but working example can be found in this Gist.