Goose Goose - 1 year ago 73
Javascript Question

Event handler inside event handler is multiplying

I have this code

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

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
twice and thus run
. Each click adds a change event handler.
should only be run once for each time
is changed. How can I prevent this unexpected behavior?

Answer Source

You should use one method instead:

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