Customizing file upload element by using associated label workaround

Today I got a defect to fix which is “File Upload functionality is not working  when using IE9”. Oh IE9 again!!.

I just wanted to show a nice and consistent UI for file input element and as there is no standard way to customize it with my own text and look, I used a button to trigger the file input’s click event and made file input hidden by setting its height and width to zero as you can see at the below code sample:

<a href="#" onclick="showFileUpload()">Click to choose file</a>

<input type="file" id="fileUpload" style="height:0; width:0;"/>
    var showFileUpload = function() {

Also here is jsFiddle

That is working in every browser but not in IE9. After some investigation I found that “Access is denied” exception is raised by IE9 when calling file input’s click from JavaScript!!

Why this happens? It is bug in IE9 as it should only prevent developer’s code from changing the content of the file input (which file to upload should be chosen through browse dialog by the user) and that seems a nice security feature but not preventing invoking other functions like click.

The issue as follows IE9 catches file input’s click invocations in JavaScript code as security breach!!

I tried to find out another workaround to get the same result. I ended up using associated label for file input in order to fire its click event and show the files browse dialog.

That is enabled because of the default behavior of labels and their associated controls. If the user clicks on a label its control’s click event will be fired. Seems nice? yes it is. It did the trick for me 🙂

Here is the code for using a label to customize file input:

<label for="fileUpload">Click to choose file</label>
<input type="file" id="fileUpload" style="height:0; width:0;"/>

jsFiddle is here


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s