Im trying to implement dynamically hide/show on a checkbox (onChange event) using code the example section of the DataTables homepage.
function(e){
//e.preventDefault();
console.log($(this).attr('datacolumn'));
// Get the column API object
var column = table.column($(this).attr('datacolumn'));
// Toggle the visibility
column.visible( ! column.visible() );
}
However I get an error. It says table.column is "undefined"
Uncaught TypeError: undefined is not a function
I've tried changing the scope of the table-variable in order for me to interact with it in the console of Chrome. And as far as I can see it just points to a htmlcontent.
UPDATE
It worked when I specified the complete path to the object.
var column = $('#example').dataTable().api().column($(this).attr('datacolumn'))
in addition, here is a very simple script
to dynamically add toggle buttons based on table thead content
in a div on top of the table
and bind a click to toggle visibility for each
$(document).ready(function() {
var table = $('#example').DataTable();
// for each column in header add a togglevis button in the div
$("#example thead th").each( function ( i ) {
var name = table.column( i ).header();
var spanelt = document.createElement( "button" );
spanelt.innerHTML = name.innerHTML;
$(spanelt).addClass("colvistoggle");
$(spanelt).attr("colidx",i); // store the column idx on the button
$(spanelt).on( 'click', function (e) {
e.preventDefault();
// Get the column API object
var column = table.column( $(this).attr('colidx') );
// Toggle the visibility
column.visible( ! column.visible() );
});
$("#colvis").append($(spanelt));
});
} );
<div id="colvis"></div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<!-- here your col header -->
</thead>
<tbody>
<!-- here your table data -->
</tbody>
</table>