Copying rows from one table to another

Copying rows from one table to another

troyleetroylee Posts: 10Questions: 5Answers: 0

Description: I have two DataTables and I want to be able to click a row in table1 and have it appear in table2. At the moment I have this code:

$("#table1 tbody").on('click', 'tr', function() {
    let new_row = table1.row(this).data();
    table2.row.add(new_row).draw();
});

Problem: This works but only copies the data with the row. The cells in each row have a css background-color property, which I would also like to copy over. Visually, I'd be looking more for something like this:

$("#table1 tbody").on('click', 'tr', function() {
    $("#table2 tbody").append(this.cloneNode(true));
});

However, this doesn't work with redrawing the DataTable, as calling .draw() after this line of code will just make it disappear.

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    If you copy the node, not the data, then you'll preserve the styling, see here:

    $("#table1 tbody").on('click', 'tr', function() {
        let new_row = table1.row(this).node().cloneNode(true);
        table2.row.add(new_row).draw();
    });  
    

    Colin

  • troyleetroylee Posts: 10Questions: 5Answers: 0

    Interesting, I see that it works in your example, but for some reason I'm getting this error: Uncaught TypeError: Cannot set properties of undefined (setting '_DT_CellIndex')

  • troyleetroylee Posts: 10Questions: 5Answers: 0
    edited November 2021

    Ok so after some testing, I've realized that the issue comes when one of my columns is initially not visible. Is there a way to take that into account?

    Edit: I've found this thread and am using the solution of quickly changing the visibility of the hidden column. I'm sure this isn't too reliable though so I'm wondering if there are any better options.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    I'm not clear why that would affect it. Please can you update my example to demonstrate your situation,

    Colin

Sign In or Register to comment.