$(document).ready(function() { var table = $('#example').DataTable(); // build tag section var totalColumns = table.columns().count(); var $toggleSection = $('<div class="datatable-column-toggles tag-group"></div>'); for (var i=0; i < totalColumns; i++) { $toggleSection.append('<div class="tag tag-active tag-checkmark-btn toggle-vis" data-column="' + i + '">' + $(table.column(i).header()).text() + '</div>'); } $toggleSection.prepend('Toggle columns: '); $('.dataTables_wrapper').before($toggleSection); $('.toggle-vis').on( 'click', function (e) { e.preventDefault(); // Get the column API object var dataColumn = $(this).attr('data-column'); var column = table.column(dataColumn); //var columnTitle = $(table.column(dataColumn).header()).text(); //var totalColumns = table.columns().count(); // Toggle the visibility column.visible( ! column.visible() ); // Update tag if (column.visible()) { $(this).removeClass('tag-close-btn tag-border-n4 text-n4'); $(this).addClass('tag-checkmark-btn'); } else { $(this).removeClass('tag-checkmark-btn'); $(this).addClass('tag-close-btn tag-border-n4 text-n4'); } } ); } );
<table class="table responsive">