?> Datatables toggle columns using checkbox

Datatables toggle columns using checkbox

This example shows how you can make use of the column().visible() API method to dynamically show and hide columns in a table. Also included here is scrolling, just to show it enabled with this API method, although that is not required for the API function to work.

In addition to this, groups of columns can be shown and hidden at the same time using the columns() method to select multiple columns and then using the columns().visible() method to set their state.


JavaScript

Initialise datatables:

  $(document).ready(function() { 

var Table = $('#table').DataTable({
"order": [[1, "desc"]],
"responsive": true,
"columns": [
{title: "Column 1", data: "Column1"},
{title: "Column 2", data: "Column2"},
{title: "Column 3", data: "Column3"},
{title: "Column 4", data: "Column4"},
{title: "Column 5", data: "Column5"},
{title: "Column 6", data: "Column6"}
]
});
});

Controls the visibilty of the column depending on whether the checkbox is ticked or not

  $(document).on('change', '.toggleOptions :checkbox', function() {
var column = table.column( $(this).attr('data-column') ); // Get the column API object
column.visible( ! column.visible() ); // Toggle the visibility
});

HTML:

  <input type="checkbox" checked id="Column1" data-column="0" class="toggle-vis columns">Column 1  <input type="checkbox" checked id="Column2" data-column="1" class="toggle-vis columns">Column 2  <input type="checkbox" checked id="Column3" data-column="2" class="toggle-vis columns">Column 3  <input type="checkbox" checked id="Column4" data-column="3" class="toggle-vis columns">Column 4  <input type="checkbox" checked id="Column5" data-column="4" class="toggle-vis columns">Column 5  <input type="checkbox" checked id="Column6" data-column="5" class="toggle-vis columns">Column 6  

data-column=" " refers to the column order of the table headings. Ensure you get these correct otherwise the incorrect column will hide, causing confusion. Remember it starts from 0 and not 1. So the first column in the table is 0, second column is 1 etc.

Top