I am trying to trigger a click event on input type="file" on the click of an another button.
Demo: http://jsfiddle.net/Y85g6/
It's working fine in all browsers except on safari browsers in mac, Ipad & Iphone.
Is there any trick to accomplish this task?
The following approach did the trick for me:
$(".upload_on_click").each(function(index) {
var form = $(this).next("form");
//form.hide(); /* THIS TECHNIQUE DIDN'T WORK IN SAFARI */
form.css("position", "absolute");
form.css("visibility", "hidden");
$(this).css("cursor", "pointer");
$(this).click(function() {
$('input[type="file"]', form).trigger("click");
});
$('input[type="file"]', form).change(function() {
$('input[type="submit"]', form).trigger("click");
});
});
Instead of trigger("click")
you can use the following code which works successfully in all browsers:
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true);
document.getElementById(elem_id).dispatchEvent(evt);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With