3

i want to call click event of file input only by jquery, but when i use this below code, it doesn't work:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="js/jquery.js"></script>
    <script>
        $(function () {
            setTimeout(function () {
                $('#file').trigger('click');
            }, 2000);
        });
    </script>
</head>
<body>
    <input id="file" name="file" type="file" />
</body>
</html>

NOTE

I want to do this only with jquery or javascript.

Rasool Ghafari
  • 4,128
  • 7
  • 44
  • 71
  • possible duplicate of [Programmatically trigger "select file" dialog box](http://stackoverflow.com/questions/8595389/programmatically-trigger-select-file-dialog-box) – technophobia May 12 '15 at 18:56
  • A very important note here regarding triggering the file input programatically: http://stackoverflow.com/a/21583865/984275 – technophobia May 12 '15 at 18:57

1 Answers1

9

Just do it!

With jQuery:

$('#file').click();

Pure javascript:

var fileInput = document.getElementById('file');
if(fileInput) {
     fileInput.click();
}

$(document).ready(function() {
  $('#btn').click(function() {
    // Will Work!!!!
    $('#fileInput').click();
  });
  // Will not Work
  $('#fileInput').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<input type="file" id="fileInput" />
<br/>
<br/>
<button id="btn">Click</button>

Your problem is that I need to call the click event from a user action. Take a look in the example. The click called inside the ready event doesn't work, because is not a user event. But the same code from click work.

Victor
  • 8,309
  • 14
  • 80
  • 129