Programmatically trigger "select file" dialog box

If you're looking to have your own button to upload a file instead of using <input type="file" />, you can do something like:

<input id="myInput" type="file" style="visibility:hidden" />
<input type="button" value="Show Dialog" onclick="$('#myInput').click();" />

Note that I used visibility: hidden, instead of display: none. You cannot call the click event on a non-displayed file input.


Most answers here are lacking a useful information:

Yes, you can programmatically click the input element using jQuery/JavaScript, but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER!

So, for example, nothing will happen if you, the script, programmatically click the button in an ajax callback, but if you put the same line of code in an event handler that was raised by the user, it will work.

P.S. The debugger; keyword disrupts the browse window if it is before the programmatical click ...at least in chrome 33...


Just for the record, there is an alternative solution that does not require javascript. It is a bit of a hack, exploiting the fact that clicking on a label sets the focus on the associated input.

You need a <label> with a proper for attribute (points to the input), optionnaly styled like a button (with bootstrap, use btn btn-default). When the user clicks the label, the dialog opens, example :

<!-- optionnal, to add a bit of style -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

<!-- minimal setup -->
<label for="exampleInput" class="btn btn-default">
  Click me
</label>
<input type="file" id="exampleInput" style="display: none" />

I'm not sure how browsers handle clicks on type="file" elements (security concerns and all), but this should work:

$('input[type="file"]').click();

I've tested this JSFiddle in Chrome, Firefox and Opera and they all show the file browse dialog.