Bug Tracker

Opened 11 years ago

Closed 11 years ago

Last modified 8 years ago

#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:
Blocked by: Blocking:

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 (3)

comment:1 Changed 11 years ago by dz

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

comment:2 Changed 11 years ago by john

Component: unfilledcore
Resolution: invalid
Status: newclosed

The other option is to use .clone(true) which clones the events along with the element itself.

comment:3 Changed 8 years 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.

Note: See TracTickets for help on using tickets.