4

I have the following JS

$(document).ready(function() { var table = $('#example').DataTable( { "scrollY": "200px", "paging": false } ); $('a.toggle-vis').on( 'click', function (e) { e.preventDefault(); // Get the column API object var column = table.column( $(this).attr('data-column') ); // Toggle the visibility column.visible( ! column.visible() ); } ); } ); 

JSFiddle or DataTablesExample

Which produce the following table that allows user to toggle the six columns by clicking on the link next to Toggle column.

enter image description here

What I want to do then is to make the table to show only Name and Position column as default and hide the rest of columns. Only when the user toggle their preferred other columns then they will appear. How can this be achieved?

In reality I have ~50 columns to show. Currently it overflow the page. Not sure what's the best way to display such case.

2 Answers 2

3

With ColVis

You need to use ColVis extension for Datatables.

Most likely you would want to hide some columns initially, you can do that using the code below.

var oTable = $('#example').DataTable({ "dom": 'C<"clear">lfrtip', "columnDefs" : [ { "targets": [4,5], "visible": false } ] }); 

See this JSFiddle for demonstration.

Also ColVis extension allows you to group columns and toggle group visibility instead of individual columns which could be helpful if you have 50 fields.

If you have that many fields, I would also consider showing extra details or responsive extension along with ColVis, you may be able to integrate these together.

Without ColVis

It can also be done without ColVis using the code below:

HTML

<p>Toggle: <a href="javascript:;" class="column-toggle" data-id="4">Start date</a> | <a href="javascript:;" class="column-toggle" data-id="5">Salary</a></p> <table id="example" class="display" cellspacing="0" width="100%"> <!-- skipped --> </table> 

JavaScript

var oTable = $('#example').DataTable({ "dom": 'lfrtip', "columnDefs" : [ { "targets": [4,5], "visible": false } ] }); $('a.column-toggle').on('click', function(e){ var column = oTable.column($(this).data('id')); column.visible(!column.visible()); e.preventDefault(); }); 

See this JSFiddle for demonstration.

Sign up to request clarification or add additional context in comments.

Comments

0

You could show the remaining information in the child table

see: https://www.datatables.net/examples/api/row_details.htmlChild Table

1 Comment

No. This is dealing with rows. My problem is the column overflow.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.