9

Possible Duplicate:
In JavaScript can I make a “click” event fire programmatically for a file input element?

I have naively tried the following to open the file picker programmatically with JavaScript (see fiddle here):

<input type='file'>​

<script>
    $(function () {
        $('input').click();
    });
</script>

The above doesn't work. How can I open the file picker of a input type='file' with JavaScript?

Community
  • 1
  • 1
Randomblue
  • 112,777
  • 145
  • 353
  • 547

2 Answers2

14

For security reasons you can't trigger the dialog, unless it is as a response to some user triggered event. You could for instance trigger the dialog through a click on some other element:

$(function () {
    $(".someElement").click(function () {
        $('#f').click();
    });
});

Working example.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
5

As a security measure, you can only open such dialogs on an user input, such as a click event (on whatever element). You cannot open it randomly such as on page load.

http://jsfiddle.net/fEBFp/2/

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 2
    I think it's it's a little odd there's no security exception in the console, though. – Jared Farrish Aug 26 '12 at 21:29
  • 3
    Responding to user input works fine cross-browser, just one thing though. If the file input has `display:none` or `visibility:hidden`, the dialog may not open in older browsers. Here's a [fiddle](http://jsfiddle.net/ult_combo/fEBFp/3/) using an example of alternative masking without `display`/`visibility` CSS. – Fabrício Matté Aug 26 '12 at 21:37
  • Thank you. In Chrome I put the file input into a 0x0px div now. In Firefox it's not even necessary to insert the file input into the document. – Robert Aug 30 '12 at 10:36