Reputation: 5193
I have a table where i can add rows using clone function like this:
new_row = $(table_id+' tbody > tr:last').clone(true).removeAttr('id').insertAfter(table_id+' tbody > tr:last');
each row have special cell which content creates manualy like this:
$(new_row).children('.action_2').html('<a class="row_delete"><img src="/images/pack/cross.png" alt="Cancel" /> Cancel</a>');
The problem is that function $('.row_delete').click(function(){...})
is not working with this dynamically added rows, what's wrong?
Upvotes: 0
Views: 249
Reputation: 6146
You need to use the .live function ( .live('click', function(e){/stuff/}); ) (and to remove the handler, use .die() )
Reason for this is that bind, adds a click handler to every element specified (with the .row_delete class in your example), and the elements that are added later, are unnafected.
Live(), binds the handler much higher, and then checks if the registered click happened in one of the specified elements.
Keep in mind that if there is another specified handler on the element, that prevents propagation of the event (or bubbling in IE language) then live()'s callback won't be called.
Upvotes: 1
Reputation: 360046
Use .live()
or .delegate()
instead of .click(...)
.
.live()
:Attach a handler to the event for all elements which match the current selector, now and in the future.
.delegate()
:Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
The event binding code would then look like
$('.row_delete').live('click', function(){...});
// or
$('#my_table_id').delegate('.row_delete', 'click', function(){...});
Upvotes: 0
Reputation: 13756
use jQuery live method to assign events, for example
$('tr').live('click', function() {
///your code here
});
so when ever you add at that place new tr event will be attached to it.
Upvotes: 0
Reputation: 8649
The click function is being applied to the rows with that class at the page load.
You have to use the live() method to get that working:
With live you can make that all the elements that match a given pattern during the entire life of the page have the same behavior.
$('.row_delete').live('click',function(){...})
That should do it.
Upvotes: 0