Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery trigger click not working on safari browsers in mac, Ipad & Iphone

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?

like image 735
Mandeep Pasbola Avatar asked Jan 19 '12 15:01

Mandeep Pasbola


2 Answers

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");
    });
});
like image 158
John Erck Avatar answered Oct 29 '22 04:10

John Erck


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);
like image 22
Sattu Avatar answered Oct 29 '22 04:10

Sattu