kodfire
kodfire

Reputation: 1783

jQuery - After clicking parent of file input and triggering click event to file input it returns 'too much recursion'

I have this in my jQuery:

$(document).on('click', '.upload-wrap', function(event)
{
    $('[name="uploads[]"]').trigger('click');
});

but it returns 'too much recursion' error! however it doesn't for my other elements like:

$(document).on('click', '.upload-image-wrap', function(event)
{
    $(this).next('[name="image"]').trigger('click');

});

I have used setTimeout either to fix this:

$(document).on('click', '.upload-wrap', function(event)
{
    setTimeout(function() {
        $('[name="uploads[]"]').trigger('click');
    }, 0);
});

But now firefox shows top of the page that 'Firefox prevented this site from opening 99999999 pop-up windows' in which 99999999 is increasing by miliseconds.

How can I fix it?

Thanks

Upvotes: 2

Views: 154

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

If a .upload-image-wrap has the '[name="uploads[]"]' attribute, you might use not() to exclude the '[name="uploads[]"]' from triggering the delegated event:

$(document).on('click', '.upload-wrap:not([name="uploads[]"])', () => {
  $('[name="uploads[]"]').trigger('click');
});

Another option would be to check if the event was triggered by a human:

$(document).on('click', '.upload-wrap', (e) => {
  if (e.originalEvent !== undefined) $('[name="uploads[]"]').trigger('click');
});

Upvotes: 1

Related Questions