Hide Columns After Reorder
Hide Columns After Reorder

The following code implements reordering, filtering, and hiding. However, after reordering hiding doesn't work because the indices of the columns are coded into the data-columns
attribute. Has anyone created a working solution to this I can study or use that allows hiding after reordering?
Also curious if there is a way to toggle the columns in a manner other than having to hard code them by name into the <div>
. Wondering if those can somehow be taken directly from the table and populated into a <div>
without manually creating it.
Example HTML table can be found here:
https://datatables.net/examples/api/show_hide.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/colreorder/1.5.2/css/colReorder.dataTables.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/colreorder/1.5.2/js/dataTables.colReorder.min.js"></script>
</head>
<title>My Application</title>
<body>
<script>
$(document).ready(function() {
$('#example thead tr').clone(true).appendTo( '#example thead' );
$('#example thead tr:eq(1) th').each( function () {
var title = $('#example thead th').eq( $(this).index() ).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('#example').DataTable( {
orderCellsTop: true,
fixedHeader: true,
colReorder: true
} );
// Apply the filter
$("#example thead input").on( 'keyup change', function () {
table
.column( $(this).parent().index()+':visible' )
.search( this.value )
.draw();
} );
$('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() );
} );
} );
</script>
<div>
Hide column: <a class="toggle-vis" data-column="0">Name</a> - <a class="toggle-vis" data-column="1">Position</a> - <a class="toggle-vis" data-column=
"2">Office</a> - <a class="toggle-vis" data-column="3">Age</a> - <a class="toggle-vis" data-column="4">Start date</a> - <a class="toggle-vis" data-column=
"5">Salary</a>
</div>
<!--Get html table -->
</body>
</html>
This question has an accepted answers - jump to answer
Answers
One option is to use the column visibility buttons which will handle this themselves,
Another is to use named columns - through the
columns.name
option. Then instead ofdata-column=0
you can use the column name as part of the selector - seecolumn-selector
.Allan
@allan , thank you and confirming the buttons approach works. I have styling questions but will post in a separate thread.