How to swap datatables columns

903 views Asked by At

So I'm getting data from an API. This data has 13 different columns, but on my datatables table I only want to show 4 at a time. To come up with a clean solution to this from a ux perspective, I built a dropdown where a user could select one of the 13 columns to switch the data with. Unfortunately I can't see anyway to do this so please help.

Here's what I've tried so far:

  • Set all not visible columns to visible:false and make them visible when they're called upon. Then make the column it's being switched with invisible
  • colReorder
  • clear the table, use jquery to modify the dom header to the correct title, then reinitialize the table with that column. This didn't work because the data has to be in the same order as it was before the user swapped the column
1

There are 1 answers

0
Mart Hagedoorn On BEST ANSWER

You can do it with the jQuery functions .hide and .show. The way I did this was by finding the index of the header title in that column. By for example:

(table).find('th').index($(table.find('th:contains(' + select + ')')))

Where select is your header title of the active or nonactive column.

Then with:

table.DataTable().column(j).visible(false);

You can hide that column, (visisble(true) to show that column). Where j is the index + 1, to account for the control column. It is a bit of hacking in the html, but it works.