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?

6
  • @JaredFarrish: jQuery or not, I don't care. Commented Aug 26, 2012 at 21:25
  • For security reasons, you can't do that. Commented Aug 26, 2012 at 21:26
  • But your example is jQuery? If it doesn't matter, do a native DOM method version as an example. Commented Aug 26, 2012 at 21:26
  • Is this what you want. Commented Aug 26, 2012 at 21:30
  • What is the purpose of doing this? Do you want to hide the default input, so that you can style some other element to trigger the dialog, or why? Commented Aug 26, 2012 at 21:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

3 Comments

I think it's it's a little odd there's no security exception in the console, though.
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 using an example of alternative masking without display/visibility CSS.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.