Douglas F Shearer

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.


<span="myfileinput"><input type="file" name="myfile" /></span>
<a href="" id="clearmyfile">clear</a>

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.

 

Comments


There are no comments.

Add Your Comments


Commenting is closed for this entry.

 

You Are Here


Douglas F Shearer

This is the homepage of Douglas F Shearer, a software developer and mountainbike racer. More…

Hire Me!


I'm available for hire. Ruby, Java and PHP work, both remotely (Worldwide) and locally (Scotland). Find out more or email me.

Flickr Latest


Stay Informed


What is RSS?

Categories


  1. Bike (93)
  2. Coding (85)
  3. Other (46)

Top Tags