You are viewing limited content. For full access, please sign in.

Question

Question

JQuery on() does not work with file upload fields when event handler is delegated

asked on April 22, 2015 Show version history

I'm trying to attach an event handler to dynamically added elements (i.e. rows that are added to a table), and the best practice is to use JQuery event delegation using on(). However, I can't seem to get it working. Below is the code:

$(document).ready(function() {

    $('.fileuploader').on('change', function() {
        // works fine
    });

    $(document.body).on('change', '.fileuploader', function() {
        //does not work
    });

});

What is more strange is that this only seems to be an issue with the file upload field. If I use ".singleline" as the selector, both event handler blocks work.

To reproduce, simply create a new form with a table, and make one of the fields inside the table a file upload field. Add some console.log statements into each block and then go to the form and add a file. You should see that only one of the blocks run.

0 0

Answer

SELECTED ANSWER
replied on April 22, 2015

I was able to get around this using the DomNodeInserted event type:

$(document.body).on('DOMNodeInserted', '.files', function(e) {
    if ($(e.target).is('tr')) {
        // do stuff
    }
});

Basically it's looking for new table rows inserted into the file tables under each upload field in order to detect when a new file has been uploaded. It's not a perfect solution but it will have to do for now. I hope this proves useful to others!

1 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.