Proper deletion of rows after adding rows with row.add()

Proper deletion of rows after adding rows with row.add()

bilyejdbilyejd Posts: 6Questions: 4Answers: 0

I am trying to create a rudimentary tree grid type structure using Datatables (I've searched this site and others, I know it is not a built-in capability). I have been able to add the rows I want after clicking on the ProjectID cell in my table (expanding the tree). However, I would like to remove the rows when I click on the parent ProjectID cell (collapsing the tree). When I try to do this, it does not delete the rows I expect it to. I think this has something to do with the row index getting messed up.

JSFiddle

Note in the JSFiddle I am using data supplied in the Javascript. In my real script I am quering a MySQL database to find the appropriate data to add, in a very similar manner as the Editor basic initialization example. I'm not sure if this adds any issues; however, the JSFiddle shows the same behavior as my actual site. Any help is appreciated.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,686Questions: 1Answers: 10,500 Site admin
    Answer ✓

    I think the issue here is that whenever you do a row().remove() call, DataTables will change its internal indexing of the rows to keep them sequential (rather than as a spare array). This I believe it ultimately wrong and will change in the next major version of DataTables.

    In the mean time, what I would recommend is that you use row().nodes() to get an array of the table nodes and then loop over that. Use the row nodes to get the data for each row (row().data()) to check if you want to delete it and then row().remove() to actually do the remove. Only call draw() once the loop is complete.

    Its a bit awkward at the moment - sorry!

    Allan

  • bilyejdbilyejd Posts: 6Questions: 4Answers: 0

    Allan,

    Thanks for your insight. I used the rows().nodes() and row().data() approach, but found that it still skipped rows during deletion.

    Try 1 JSFiddle

    I ended up having to create a function to remove rows, then call that multiple times to remove all the "child" rows. I also created a function to test whether the row ProjectID has the same "root" as the row that is being collapsed (so clicking ProjectID 1.3 should now collapse 1.3.1, 1.3.2, etc.).

    Final JSFiddle

    This seems to provide the functionality I'm looking for. I hope that the multiple loops through the table will not create a significant performance impact when the table gets larger. While there is still much more to do on this, I now have a proof of concept to continue development on my real site. Thanks again Allan!

This discussion has been closed.