on click handler doesn't work after a refresh of the data

on click handler doesn't work after a refresh of the data

abh555abh555 Posts: 6Questions: 2Answers: 0

I'm building an HTML table via Javascript DOM, then initializing it with datatables, including hooking the click event to track the number of selected rows. Works as expected. When I want to refresh the data though, something happens to the click handler. The handler runs, the rows visually select / deselect, but the count of selected rows returns zero. I experimented with a number different concepts for initializing the datatable (i.e., avoiding a second initialization entirely, and using "destroy" or "retrieve"), but neither resolved the issue. Can someone point me in the right direction?

live.datatables.net/yaganalo/1/edit

(Show the console, click some rows, click the "refresh" button, then click rows again.)

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,118Questions: 1Answers: 2,583

    Hi @abh555 ,

    The problem was because you were removing the rows, but not re-adding them - so in your example, if you reordered a column, it would show it as empty. The fix is to destroy the table, as shown here.

    It would also be worth looking at the Select extension, as this is likely to do what you want too.

    Cheers,

    Colin

  • abh555abh555 Posts: 6Questions: 2Answers: 0

    Thanks Colin. Your updated sample doesn't work, but that appears to be because the line "bDTInitialized = true" is commented out in the initializeDatatable function. With that line added back in, it works as expected both before and after the refresh.

    I'm a little confused about one point though -- you indicated I wasn't adding the rows back in, but they were added in after the refresh the same way they were added before the refresh. Is it not valid to use DOM to add directly to the HTML table after datatables has been initialized and worked its magic on the HTML table?

  • colincolin Posts: 15,118Questions: 1Answers: 2,583
    Answer ✓

    Hi @abh555 ,

    Odd, that example was working fine for me, still - as long as it's working for you!

    Yep, you were adding them in refreshItemList(), but that's adding it to the DOM, not the DataTable - DataTables was unaware that new rows had been added. To add to the DataTable, either use row.add(), or, add them as you did, and force DataTables to rescan the table with rows().invalidate(),

    Cheers,

    Colin

  • abh555abh555 Posts: 6Questions: 2Answers: 0

    Understood, and thanks again!

This discussion has been closed.