1

I'm trying to call the click() method of a file input with a specific id, but the function call returns undefined and basically, nothing happens. I've replicated the situation here: http://jsfiddle.net/gkaG2/

It's very simple:

HTML

<input id="hiddenFileInput" type="file" multiple="multiple" accept="image/*" >

Javascript

document.getElementById('hiddenFileInput').click();
alert(document.getElementById('hiddenFileInput').click());

I try calling the click() method on the element, which doesn't work. I then call alert() to print what the function returns when it's called. It returns "undefined." I'm obviously doing something wrong, but what exactly?

2 Answers2

1

You can't emulate click on input type=file. It's forbidden. It works only inside another onclick handler. The user must click on something to open the dialog.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • 1
    From what I understand Riateche, that's not true. Here's a demo provided by Mozilla: https://developer.mozilla.org/samples/domref/file-click-demo.html – Alexander Kuznetsov May 19 '13 at 19:51
  • It works only inside another onclick handler. The user must click on something to open the dialog. – Pavel Strakhov May 19 '13 at 19:57
  • Oh, that would explain a lot. I had it working earlier, but only when a user clicked on a button. Now that I tried to call it when the page loaded, it wasn't working, and I couldn't figure out why for the life of me. Thank you very much. – Alexander Kuznetsov May 19 '13 at 20:02
0

This is a security issue. To prevent your Browser to select files for you, you can't simulate click events. See this: In JavaScript can I make a "click" event fire programmatically for a file input element?

Community
  • 1
  • 1
Zim84
  • 3,404
  • 2
  • 35
  • 40
  • 1
    Thank you very much for the response, Zim84. It turns out it is possible to call the click method on a file input, but as Riateche said, only if the user clicks on something to open the dialog. – Alexander Kuznetsov May 19 '13 at 20:04