I'd like to make a click event fire on an <input type="file">
tag programmatically.
Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.
I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.
You can fire click() on any browser but some browsers need the element to be visible and focused. Here's a jQuery example:
It works with the hide before the
click()
but I don't know if it works without calling the show method. Never tried this on Opera, I tested on IE/FF/Safari/Chrome and it works. I hope this will help.You cannot do that in all browsers, supposedly IE does allow it, but Mozilla and Opera do not.
When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.
I don't know why you cannot do it, but one thing that is a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.
THIS IS POSSIBLE: Under FF4+, Opera ?, Chrome: but:
inputElement.click()
should be called from user action context! (not script execution context)<input type="file" />
should be visible (inputElement.style.display !== 'none'
) (you can hide it with visibility or something other, but not "display" property)I had a
<input type="button">
tag hidden from view. What I did was attaching the"onClick"
event to any visible component of any type such as a label. This was done using either Google Chrome's Developer Tools or Mozilla Firefox's Firebug using the right-click "edit HTML" command. In this event specify the following script or something similar:If you have JQuery:
if not:
Thanks.
There are ways to redirect events to the control but don't expect to be able to easily fire events to the fire control yourself as the browsers will try to block that for (good) security reasons.
If you only need the file dialog to show up when a user clicks something, let's say because you want better looking file upload buttons, then you might want to take a look at what Shaun Inman came up with.
I've been able to achieve keyboard triggering with creative shifting of focus in and out of the control between keydown, keypress & keyup events. YMMV.
My sincere advice is to leave this the alone, because this is a world of browser-incompatibility-pain. Minor browser updates may also block tricks without warning and you may have to keep reinventing hacks to keep it working.
You can use