Reputation: 7969
I've got a big complicated method bound to all inputs on a page. Sometimes, however, inputs are dynamically added to the page and therefore arn't bound to the same method. I thought that I could be clever by binding the event to a variable, and updating the variable with the additional inputs as they're added to the page... but no.
I.e.
inputs.click(function(){ // stuff });
// add inputs to page
inputs = $('input');
Is there a sneakier way to do this? OBV I can throw the whole shebang ($('input').click()...)
in a function and reinitliaze that way... but surely there's a better way?
Upvotes: 0
Views: 35
Reputation: 253486
You have to bind events to elements that are already on the page so use on()
and bind to the closest ancestor of the dynamic inputs that is already present on the page, such as the form itself:
$('form').on('change', 'input', function() {
// do something
});
The first string is a white-space separated list of events on which to react, the second is a jQuery selector to identify the targets of the events (if not the form
itself).
References:
on()
.Upvotes: 1