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.

2

1 Answer 1

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.

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

5 Comments

@RasoolGhafari what isn't working for you what error message are u getting if any?
@RasoolGhafari I think it must be triggered by a user event like a user clicking another button...I don't think it will work in setInterval().
@Victor, i know that way, but i want to trigger click without user action
I fixed the example. It's a security issue.
Without an user action I don't know if you can do it. With a delay, take a look in this example: jsfiddle.net/eyedean/1bw357kw

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.