Ticket #4165 (closed bug: invalid)
Creating new button through clone() method does not work.
| Reported by: | kunalkeane | Owned by: | |
|---|---|---|---|
| Priority: | major | Milestone: | 1.3.2 |
| Component: | core | Version: | 1.3.1 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
I created a new row by cloning existing row. Original row contains one text field and one submit button "Add Row" to add new row. Pressing button in original row calls a function and clones the row however Pressing Button from cloned row does not call the function. Any clues?
Change History
comment:2 Changed 4 years ago by john
- Status changed from new to closed
- Resolution set to invalid
- Component changed from unfilled to core
The other option is to use .clone(true) which clones the events along with the element itself.
comment:3 Changed 14 months ago by anonymous
Just wanted to add a comment to explain a bit further.
With jQ 1.7 .live() and many other "shortcuts" are depreciated, and call on .on() instead. I had an almost exact issue to this problem where I was cloning a table row, with an Add Row button in the last cell. I wanted to click the Add Row button, have it clone the row, with the button then remove the button on the row before.
With .on() you need to remember that the events bubble up, so attaching the .on() or .live() events to the button in the first row, will only "bubble" up to that button, instead you need to attach the listener to the table or tbody instead of the button or row. ex,
$('table').on('click', 'button.add_row', function(e) {}); This works.
I was attaching the event listener to the button itself $('button.add_new').on('click', function(e){
clone the last tr $(this).remove();
});
It took me a while to figure out that the event handler for 'click' was only attached to the original button, when the new button was cloned I had removed the original button, hence also removing the event handler that was bound to it.
I hope this helps others later on that come across this issue.
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

Not a bug. Use live events, since you're adding new elements to the dom that didn't have that click event bound originally.
For example, this works using .live():
http://jquery.nodnod.net/cases/126