Rasool Ghafari
Rasool Ghafari

Reputation: 4258

How to call file input click with jquery?

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.

Upvotes: 3

Views: 7932

Answers (1)

Victor
Victor

Reputation: 8480

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.

Upvotes: 9

Related Questions