Press page and at the end click on a button automatically

Asked

Viewed 1,329 times

1

I would like the page to be automatically clicked on the button fileToUpload, in the following code:

<body>

  <form name="form5" id="form1" enctype="multipart/form-data" method="post" action="Upload.aspx">

    <div>
      <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" accept="image/*" capture="camera" />
    </div>

    <div>
      <input type="button" onclick="uploadFile()" value="Upload" />
    </div>
  </form>
<!-- fiz esse código abaixo mas não funciona-->
<script type="text/javascript">
    document.form5.getElementById("fileToUpload").click();
</script>

</body>
  • You are currently using pure Javascript or jQuery ?

2 answers

1

This is not possible crossbrowser for security reasons. Browsers are increasingly restricting access to files.

The only way to open this file checkbox is following a user action. That is, if there is an event on the page it is possible to "transfer" it to open the window (example: http://jsfiddle.net/7j0j9qpu/1/).

But it will not work if it is an event created without user action (example: http://jsfiddle.net/7j0j9qpu/ that does not work on Chrome 46 on mac).

0

Using the scripts below you can run the event by clicking on a input of the kind file, but only in some browser with older versions, as mentioned in this question Soen. So it won’t help you but it will be a reference if someone needs it.

$(document).ready(function() {
    $('#fileToUpload').trigger('click');
});

document.addEventListener('DOMContentLoaded', function() {
   document.getElementById('fileToUpload').click();
});
  • you tested that code? it doesn’t work for me... http://jsfiddle.net/7j0j9qpu/

  • @Sergio worked here... https://jsfiddle.net/devgaspa/7spdp9xm/, why didn’t it work there ?

  • In your example you use a button, in my use input[type=file], I think the browser prevents for security reasons. I am using Chrome on Mac.

  • @Sergio so this way is unfeasible, I will try other alternatives.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.