william007
william007

Reputation: 18545

Preventing adding multiple event handler

I have a file input

<input type=file class=file-input/>

it has originally one on the page and it can be dynamically created by clicking the "add" button on the page, during each add, I do the following:

$(".file-input[type=file]").change(alert("hello"))

Say I click the add once, I would have two file input on the page. I would get two alert when clicking the first file input, while one alert when clicking second file input, reason is I have added twice the alert("hello") to the onChange event of first file input, while once for second file input.

is there a way to make it so that each file input only alert("hello") once?

Upvotes: 3

Views: 1051

Answers (3)

Ahmed El Kilani
Ahmed El Kilani

Reputation: 345

You have to do it once in the initialization of the page.

As a workaround solution use off() to detach previous handlers:

$(".file-input[type=file]").off('change').on('change',function(){
alert("hello");
});

Upvotes: 2

James Montagne
James Montagne

Reputation: 78650

There are a few options. One would be to use event delegation with jquery's on. In this way, you attach the handler to a common parent once at the beginning and then don't need to re-attach when new ones are created. Something like this:

$("<some common parent>").on("change", ".file-input[type=file]", function(){
    ...
});

The common parent here can be document if absolutely necessary. Ideally though, this should be some selector which is common to all file inputs.

Another option is to simply attach the event to the individual element at the time of creation:

$("<input>")... stuff  
    .change(...)

In this way you would only attach to that one element instead of all existing elements.

Upvotes: 5

user149341
user149341

Reputation:

Instead of trying to rebind each newly created element, you can bind a single event to apply to any matching element, current or future, using $.on():

$(document).on("change", ".file-input[type=file]", function(event) {
    alert("hello");
});

You only need to do this once on page load.

Upvotes: 1

Related Questions