Goose
Goose

Reputation: 4821

Event handler inside event handler is multiplying

I have this code

jQuery('#parent').on('click', jQuery('#fileInput'), function (e) {
    jQuery(e.target).attr('data-fileurl', '');
    jQuery('#parent').on('change', jQuery('#fileInput'), function (e) {
        usefulFunction(jQuery(e.target);
    }
}

The idea is to detect if cancel was chosen on file browse, and it succeeds at that.

The problem is if I click it again, then it will run the .on('chance') twice and thus run usefulFunction. Each click adds a change event handler. usefulFunction should only be run once for each time jQuery('#fileInput') is changed. How can I prevent this unexpected behavior?

Upvotes: 0

Views: 195

Answers (1)

antyrat
antyrat

Reputation: 27765

You should use one method instead:

jQuery('#parent').one('change', jQuery('#fileInput'), function (e) {
                    ^
...

Upvotes: 2

Related Questions