How do I maintain (or reapply) jQuery binds on new elements after using jQuery "clone()"?

612 Views Asked by At

I have a form with which I use jQuery ".clone()" to add new rows. Everything looks great, however I have a binding problem. Basically, on initialization, I use the jQuery ".datepicker()" function for one field (based on class). If I use ".clone()" by itself I don't get any of the ".datepicker()" functionality with the new item. If I use ".clone(true)" I get the functionality, but for cloned rows it fills the date of the row it was cloned from, not the actual row clicked.

I've tried unbinding/rebinding, but none of this works. So, how do I append new rows to a form while still getting all of the jQuery funness to work properly?

Best

EDIT 1 (jQuery):

function addLineItem(){
    $('#charges_table tr:last').clone(true).insertAfter('#charges_table tr:last');
}

$(function(){
    $('.date_pick').datepicker({"numberOfMonths": 2});
    $("#add_line_item").bind('click',function(event){
        event.preventDefault();
        addLineItem();
        $('.date_pick').datepicker('destroy');
        $('.date_pick').datepicker();
    })
})

FYI, I'm only binding on class, and the HTML elements aren't using an ID to speak of.

2

There are 2 best solutions below

0
Jake Feasel On

When you .clone(), are you changing the ID of the element before you insert it back into the DOM? If not, your ID would be duplicated, and that could be the source of your trouble.

2
dgvid On

First, as written, your method addLineItem is always going to clone whatever the last row of the table is: $('#charges_table tr:last'). It sounds like you want to clone the table row within which the click occurred. If that is the case, then something like this should do the trick:

function addLineItem(row){
    $(row).clone(true).insertAfter('#charges_table tr:last');
}

$(function(){
    $('.date_pick').datepicker({"numberOfMonths": 2});
    $("#add_line_item").bind('click',function(event){
        event.preventDefault();
        // Pass the closest 'tr' element to the element clicked.
        addLineItem($(this).closest('tr'));
    });
});

I haven't tested this code, but it is based on similar table row cloning code in one of my projects.