Row Grouping With DataTable
Row Grouping with data table
HTML
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src=" https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
...
CSS
tr.group,
tr.group:hover {
background-color: #ddd !important;
}
JavaScript
$(document).ready(function() {
var table = $('#example').DataTable( {
"order": [[ 2, 'asc' ], [ 1, 'asc' ]],
drawCallback: function ( settings ) {
var api = this.api();
var tableRows = api.rows( {page:'current'} ).nodes();
var lastGroup = null;
var lastSub = null;
var mySubGroup = null;
$(tableRows).each( function () {
groupName = this.cells[2].innerHTML;
mySubGroup = this.cells[1].innerHTML;
if ( lastGroup !== groupName ) {
lastGroup = groupName;
}
if (lastSub !== mySubGroup) {
$(this).before('<tr class="group"><td colspan="6">'+groupName+':'+ mySubGroup +'</td></tr>');
lastSub = mySubGroup;
}
} );
}
} );
// Order by the grouping
$('#example tbody').on( 'click', 'tr.group', function () {
var currentOrder = table.order()[0];
if ( currentOrder[0] === 2 && currentOrder[1] === 'asc' ) {
table.order( [ 2, 'desc' ] ).draw();
}
else {
table.order( [ 2, 'asc' ] ).draw();
}
} );
} );