How to toggle columns on multiple tables
How to toggle columns on multiple tables

I have started using Datatables and found this link (https://datatables.net/examples/api/show_hide.html) that allows you to dynamically show and hide columns. I have two tables (with the same columns) on a page and want to have one toggle menu to manage the columns. Is this possible?
This is the code I have below:
$('a.toggle-vis').on( 'click', function (e) {
e.preventDefault();
// Get the column API object
var column = $('.datatable-toggle').DataTable().column( $(this).attr('data-column') );
// Toggle the visibility
column.visible( ! column.visible() );
} );
So far the toggle only works on the first table. I guess this is because I need loop through the tables as suggested here: https://stackoverflow.com/questions/36941420/multiple-data-table-toggle-column. Could someone help?
Thanks in advance!
Answers
You can use
tables()
for that - see example here.Colin
Hi Colin,
Thanks for your help but not sure I was clear enough. I have adapted your jsfiddle here: http://live.datatables.net/locunusi/1/edit
Now it has a toggle at the top which shows/hides the first column (Name) but only for the first table not the second.
Thanks again!
We've found a bug. My example works, but if you add a visible call afterwards, it gives an exception, see here: http://live.datatables.net/suqatana/3/edit
I've raised it internally (DD-1734 for my reference) and we'll report back here when there's an update.
In the meantime, a workaround like this should do the trick: http://live.datatables.net/locunusi/4/edit
Cheers,
Colin
Thanks Colin! I will use your workaround for now. Very helpful!