user3426204
user3426204

Reputation: 51

jQuery: Delete rows from multiple tables simultaneously

I use dynamically generated rows for the form preview, and I'm trying to remove rows in two different tables simultaneously. We say if I delete the second line (#2) on "AddFieldsToFormDiv" I want that second line (#2) on "AddFieldsToPreviewDiv" removed simultaneously. Do you have workable solution ?

Here's the js fiddle

I tried to use:

$("#AddFieldsToFormDiv, #AddFieldsToPreviewDiv")
    .on("click", "#DeleteRowButton", function (event) 
    {
        $(this).closest("tr").remove();
        counter--;
    });

but without the result I wanted.

Upvotes: 0

Views: 228

Answers (1)

Brandon Kindred
Brandon Kindred

Reputation: 1488

Well the main reason that this is only working for your AddFieldsToFormDiv table is because you are only doing any work on AddFieldsToFormDiv. This function you have here is binding a click element to both tables with #DeleteRowButton elements. The problem here is that AddFieldsToFormDiv is the only table with any of these #DeleteRowButton elements, so binding the click to the other table is completely pointless. Once we have that cleaned up, you still have to perform the remove on both tables. I modified your function for it to work.

$("#AddFieldsToFormDiv").on("click", "#DeleteRowButton",function (event) {
    var rowIdx = $(this).closest("tr").index();
    removeRowFromTable($("#AddFieldsToPreviewDiv"), rowIdx);
    removeRowFromTable($("#AddFieldsToFormDiv"), rowIdx);

    counter--;
});  

function removeRowFromTable( table,  rowIdx){
    table.find("tr").eq(rowIdx).remove();
}

Upvotes: 1

Related Questions