Sadzeih
Sadzeih

Reputation: 156

jQuery .clone(true, true) not cloning events

I'm working on this piece of code and as I'm not really good with jQuery, I found myself stuck.

var row_clone_index = 1;
function Row_clone() {
    var cloned_row = $(this).parent().parent().clone(true, true);
    cloned_row.css('display', 'none');
    cloned_row.delay(100).queue(function(next){
        cloned_row.css('display', '');
        next();
    });
    $(this).removeClass("row-clone");

    var html = cloned_row.html().replace(/new/g, "new" + row_clone_index);
    cloned_row.html(html);

    cloned_row.find("select,input").each(function() {
        if (!$(this).hasClass("preserved")) {
            if (!$(this).attr("id")) {
                $(this).val("");
            } else {
                match = $(this).attr("id").match(/((start|stop)holiday_new)[0-9]*_(calendar(month|year))/);
                if (match) {
                    id = match[1] + "_" + match[3];
                    $(this).val($("#" + id).val());
                } else {
                    if ($(this).attr("type") == "checkbox") {
                        $(this).removeAttr("checked");
                    } else if ($(this).attr("id").match(/(start|stop)holiday_new.*/)) {
                        $(this).val("");
                    } else if ($(this).attr("id").search(/day/) == -1) {
                        $(this).val("");
                    }
                }
            }
        }
    });
    $(this).parent().parent().after(cloned_row);
    row_clone_index = parseInt(row_clone_index) + 1;
};

What I'm trying to do is clone an element when it changes (the Row_clone function is called on a .change()). But the events that should happen when interacting with this element after being cloned don't happen.

I tried moving the .after at the end (it was previously at the beginning of the function but it didn't change anything).

Thanks for the help!

Upvotes: 1

Views: 881

Answers (1)

Zathrus Writer
Zathrus Writer

Reputation: 4331

It looks like you're cloning it right, however afterwards, you're also changing the HTML of the element, which does most probably invalidate all your previously cloned bindings:

var html = cloned_row.html().replace(/new/g, "new" + row_clone_index);
cloned_row.html(html);

Don't adjust the HTML directly, use find() to change the sections you need to replace by whatever needs replacing.

Upvotes: 1

Related Questions