1

I'm trying to trigger the click event of an <input type="file" /> via javascript (onclick the file selection dialogue should open). So far I've tried:

$('#uploadFile').trigger('click')
.trigger('submit')
.submit()
.post(); // Stacked for brevity

No dice.

Is there something special about this input that prevents these approaches from working?

Here's a Fiddle.

0

1 Answer 1

4

some of the default actions of events are prevented by the browser if the event is triggered by a script and is not done in a user initialized thread for security reasons.

See it working if it is triggered from a another click handler(User has to click the button)

$('button').click(function(){
    $('#uploadFile').trigger('click')
})

Demo: Fiddle

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

4 Comments

Yep, that did the trick. Any comments on cross-browser support?
@monners it should be fine if you don't have a on change handler in the file input where you submit a form
that's a good point, and that might be an issue, but this is more than enough to get me started. Thanks @ArunPJohny
Instead of this script, you can also use <label for="uploadFile">this</label> to trigger the file button on click.

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.