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.

share|improve this question
This is a duplicate of another question. "Is it possible to trigger a link's (or any element's) click event through JavaScript?" – Chris MacDonald Oct 17 '08 at 0:17
5  
Although now that I read more this is asking about input type="file" specifically... – Chris MacDonald Oct 17 '08 at 0:19
Changed the title to reflect the more specific nature of the question. – user28655 Oct 17 '08 at 0:57
Cross-browser alternative here stackoverflow.com/questions/8928386/… – Mandeep Pasbola Jan 24 '12 at 18:02

20 Answers

up vote 34 down vote accepted

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.

share|improve this answer
1  
Drat. Well I certainly understand that it's exploitable. Is this documented anywhere? I guess it would be implemented by each browser? – user28655 Oct 16 '08 at 23:47
Updated my answer to be more correct than previous answer - the gist is the same, but clarification should help a bit. This guy ran into the same problem: bytes.com/forum/thread542877.html – Jason Bunting Oct 17 '08 at 0:19
Thanks God FF5 allows this click – rshimoda Aug 9 '11 at 21:17
Yeah but Chrome does not seem to allow click() :( – Romain Guidoux Dec 28 '11 at 16:57
1  
To clarify above comment: Chrome recently changed to check whether the file input element is visible. Triggering the click method works, including in the console, if the element can be seen. – jwadsack Jan 10 '12 at 22:32
show 2 more comments

I have been searching for solution to this whole day. And these are the conclusions that I have made:

  1. For the security reasons Opera and Firefox don't allow to trigger file input.
  2. The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards create the button "bellow" it. In this way the button is seen but on user click it actually activates the file input.

Hope this helps! :)

<div style="display: block; width: 100px; height: 20px; overflow: hidden;">
<button style="width: 110px; height: 30px; position: relative; top: -5px; left: -5px;"><a href="javascript: void(0)">Upload File</a></button>
<input type="file" id="upload_input" name="upload" style="font-size: 50px; width: 120px; opacity: 0; filter:alpha(opacity: 0);  position: relative; top: -40px;; left: -20px" />
</div>
share|improve this answer
1  
this solution works great. Not sure why it's been overlooked and un-uprated. It's not *exactly what the question asks for, but it's a great work around. Have you found it to be incompatible with any browsers? I don't have the time to work my way through all 10+ flavors of relevant ones to test on. – Dr.Dredel Sep 15 '10 at 5:11
This solution is awesome. Thanks!!! – SKR Sep 21 '10 at 4:08
Fantastic solution!!! Works like charm in FF3.5+, IE8, Safari – TheVillageIdiot Apr 26 '11 at 6:49
Thank you for this answer, it's awesome :D – mario.tco Jul 20 '11 at 17:22
really cool! ;-) great answer bro – aSeptik Jul 31 '11 at 19:03
show 2 more comments

You can fire click() on any browser but some browsers need the element to be visible and focused. Here's a jQuery example:

$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();

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.

share|improve this answer
14  
Thanks for sharing. Just in case you didn't know - you can use chaining in jQuery: $(...).show().focus().click().hide(); :) – pimvdb Jul 31 '11 at 12:22
@pimvdb: as far as I test, your solution only works on Chrome. – Hoàng Long Oct 10 '11 at 8:47
@Hoàng Long: Do you mean the chaining or Florin Mogos' solution? I don't believe chaining would make any cross-browser differences. – pimvdb Oct 10 '11 at 14:28
@pimvdb: I mean Florin's solution. – Hoàng Long Oct 11 '11 at 6:37
@HoàngLong It works for me in IE 8 and 9, latest Chrome, Safari, and Firefox. – sjs Nov 29 '11 at 19:03
show 3 more comments

Try this solution: http://code.google.com/p/upload-at-click/

share|improve this answer
That looks very ugly at least on IE9. – Kyberias Mar 27 '12 at 7:56

For those who understand that you have to overlay an invisible form over the link, but are too lazy to write, I wrote it for you. Well, for me, but might as well share. Comments are welcome.

HTML (Somewhere):

<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>

HTML (Somewhere you don't care about):

<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
    </form>
</div>

JavaScript:

function pageY(el) {
    var ot = 0;
    while (el && el.offsetParent != el) {
        ot += el.offsetTop ? el.offsetTop : 0;
        el = el.offsetParent;
    }
    return ot;
}

function pageX(el) {
    var ol = 0;
    while (el && el.offsetParent != el) {
        ol += el.offsetLeft ? el.offsetLeft : 0;
        el = el.offsetParent;
    }
    return ol;
}

function fileMove() {
    if (navigator.appName == "Microsoft Internet Explorer") {
        return; // Don't need to do this in IE. 
    }
    var link = document.getElementById("fileLink");
    var form = document.getElementById("uploadForm");
    var x = pageX(link);
    var y = pageY(link);
    form.style.position = 'absolute';
    form.style.left = x + 'px';
    form.style.top = y + 'px';
}

function fileBrowse() {
    // This works in IE only. Doesn't do jack in FF. :( 
    var browseField = document.getElementById("uploadForm").file;
    browseField.click();
}
share|improve this answer

If you want the click method to work on Chrome, Firefox, etc, apply the following style to your input file. It will be perfectly hidden, it's like you do a display: none;

#fileInput {
    visibility: hidden;
    position: absolute;
    top: 0;
    left: -5000px;
}

It's that simple, I tested it works!

share|improve this answer
I like this way the best since some older browsers won't do anything on inputElement.click() if it is hidden. – Nick Karnik Jan 17 at 1:59

THIS IS POSSIBLE: Under FF4+, Opera ?, Chrome: but:

  1. inputElement.click() should be called from user action context! (not script execution context)

  2. <input type="file" /> should be visible (inputElement.style.display !== 'none') (you can hide it with visibility or something other, but not "display" property)

share|improve this answer

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.

share|improve this answer

I haven't tried this but you might be able to do it with jQuery.

$('input[type=file]:first').trigger('click')

The reason you can't just do .click() is that this is only supported for inputs of type button.

[EDIT] Ordinarily I'd test this before posting, but I've got to run and pick up my daughter. If it doesn't work, leave a comment and I'll delete my answer.

[EDIT] The following works in Safari, but not Firefox. Didn't test IE as not working in Firefox is probably a deal breaker. Probably need to find a different way of doing it.

<html>
<head>
    <script type="text/javascript" src="jquery-1.2.6.js"></script>
    <script type="text/javascript">
       function clickFileUpload() {
          $('input[type=file]:first').trigger('click');
    	}
    </script>
</head>
<body>
<form action="test_submit" method="POST" accept-charset="utf-8">
    <p>
    	<input type="file">
    </p>
    <p>
    	<input type="button" onclick="clickFileUpload();" value="Get File" />
    </p>
</form>

</body>

share|improve this answer
This probably works okay in browsers that support this for the HTML File element, but Firefox and Opera don't at this time, AFAIK. – Jason Bunting Oct 17 '08 at 0:18
this works in the latest Safari and mobile Safari – Cal S Jan 28 at 3:35

I was researching this a while ago because I wanted to create a custom button that would open the file dialog and start the upload immediately. I just noticed something that might make this possible - firefox seems to open the dialog when you click anywhere on the upload. So the following might do it:

  1. Create a file upload and a separate element containing an image that you want to use as the button
  2. Arrange them to overlap and make the file element backgroud and border transparent so the button is the only thing visible
  3. Add the javascript to make IE open the dialog when the button/file input is clicked
  4. Use an onchange event to submit the form when a file is selected

This is only theoretical since I already used another method to solve the problem but it just might work.

share|improve this answer
2  
What other method? – Marcus Downing Nov 6 '09 at 18:56

My solution for Safari with jQuery and jQuery-ui:

$("<input type='file' class='ui-helper-hidden-accessible' />").appendTo("body").focus().trigger('click');
share|improve this answer
$(document).one('mousemove', function() { $(element).trigger('click') } );

Worked for me when I ran into similar problem, it's a regular eRube Goldberg.

share|improve this answer

WORKING SOLUTION

I haven't been able to test all browsers and version yet (I'm at work & havn't used this trick in a couple years) and at home i have a modern jQuery plug for almost all new browsers (cept maybe safari, non-tested there). I'll post those later. For now, let me add to this old post, a working solution I used to use that works in probably 80% or more of all browsers both new and old.

The solution is complex yet simple. The first step is to make use of CSS and guise the input file type with "under-elements" that show through as it has an opacity of 0. The next step is to use JavaScript to update its label as needed.

HTML The ID's are simply inserted if you wanted a quick way to access a specific element, the classes however, are a must as they relate to the CSS that sets this whole process up

<div class="file-input wrapper">
    <input id="inpFile0" type="file" class="file-input control" />
    <div class="file-input content">
        <label id="inpFileOutput0" for="inpFileButton" class="file-input output">Click Here</label>
        <input id="inpFileButton0" type="button" class="file-input button" value="Select File" />
    </div>
</div>

CSS Keep in mind, coloring and font-styles and such are totally your preference, if you use this basic CSS, you can always use after-end mark up to style as you please, this is shown in the jsFiddle listed at the end.

.file-test-area {
    border: 1px solid;
    margin: .5em;
    padding: 1em;
}
.file-input {
    cursor: pointer !important;
}
.file-input * {
    cursor: pointer !important;
    display: inline-block;
}
.file-input.wrapper {
    display: inline-block;
    font-size: 14px;
    height: auto;
    overflow: hidden;
    position: relative;
    width: auto;
}
.file-input.control {
    -moz-opacity:0 ;
    filter:alpha(opacity: 0);
    opacity: 0;

    height: 100%;
    position: absolute;
    text-align: right;
    width: 100%;
    z-index: 2;
}
.file-input.content {
    position: relative;
    top: 0px;
    left: 0px;
    z-index: 1;
}
.file-input.output {
    background-color: #FFC;
    font-size: .8em;
    padding: .2em .2em .2em .4em;
    text-align: center;
    width: 10em;
}
.file-input.button {
    border: none;
    font-weight: bold;
    margin-left: .25em;
    padding: 0 .25em;
}

JavaScript Pure and true, however, some OLDER (retired) browsers may still have trouble with it (like Netscrape 2!)

var inp = document.getElementsByTagName('input');
for (var i=0;i<inp.length;i++) {
    if (inp[i].type != 'file') continue;
    inp[i].relatedElement = inp[i].parentNode.getElementsByTagName('label')[0];
    inp[i].onchange /*= inp[i].onmouseout*/ = function () {
        this.relatedElement.innerHTML = this.value;
    };
};

Working jsFiddle Example

share|improve this answer

You can do this as per answer from Open File Diaglog box on <a> tag

<input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px;     height: 1px" multiple />
<a href="" onclick="document.getElementById('upload').click(); return false">Upload</a>
share|improve this answer

See my post here:
http://stackoverflow.com/questions/143747/is-it-possible-to-trigger-a-links-or-any-elements-click-event-through-javascript#143771

share|improve this answer
Chris, you cannot do it in Firefox or Opera though, regardless. This applies specifically to the HTML File element. – Jason Bunting Oct 17 '08 at 0:18
1  
Do you mean you cannot fire that on the input type=file? – Chris MacDonald Oct 17 '08 at 0:24

This will now be possible in Firefox 4, with the caveat that it counts as a pop-up window and will therefore be blocked whenever a pop-up window would have been.

share|improve this answer
2  
Actually firefox4 improve the state of file upload a lot. My trouble is how to do the same in Google Chrome browser. – erick2red Apr 25 '11 at 15:03

This code works for me. Is this what you are trying to do?

<input type="file" style="position:absolute;left:-999px;" id="fileinput" />
<button  id="addfiles" >Add files</button>

<script language="javascript" type="text/javascript">
   $("#addfiles").click(function(){
      $("#fileinput").click();
   });
</script>
share|improve this answer
Doesn't work in all browsers (but it does work in FF 4+). – Joe Coder Feb 13 '12 at 18:09
sorry, bad code :S – Olaf Erlandsen Mar 5 '12 at 17:09

Here is solution that work for me: CSS:

#uploadtruefield {
    left: 225px;
    opacity: 0;
    position: absolute;
    right: 0;
    top: 266px;
    opacity:0;
    -moz-opacity:0;
    filter:alpha(opacity:0);
    width: 270px;
    z-index: 2;
}

.uploadmask {
    background:url(../img/browse.gif) no-repeat 100% 50%;
}
#uploadmaskfield{
    width:132px;
}

HTML with "small" JQuery help:

<div class="uploadmask">
    <input id="uploadmaskfield" type="text" name="uploadmaskfield">
</div>
<input id="uploadtruefield"  type="file" onchange="$('#uploadmaskfield').val(this.value)" >

Just be sure that maskfied is covered compeltly by true upload field.

share|improve this answer

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:

$('#id_of_component').click();

if not:

document.getElementById('id_of_component').click();

Thanks.

share|improve this answer

I found that if input(file) is outside form, then firing click event invokes file dialog.

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.