DataTables - Child rows
by Hifni Nazeer
HTML
<link rel="stylesheet" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css">
<script src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>
<h3>jQuery DataTables: Bootstap</h3>
<a href="https://www.gyrocode.com/articles/tag/jquery-datatables/">See more articles about jQuery DataTables</a> on <a href="https://www.gyrocode.com/articles/">Gyrocode.com</a><hr>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
<th>Extn.</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
<th>Extn.</th>
</tr>
</tfoot>
</table>
<hr><a href="https://www.gyrocode.com/articles/tag/jquery-datatables/">See more articles about jQuery DataTables</a> on <a href="https://www.gyrocode.com/articles/">Gyrocode.com</a>
CSS
td.details-control {
background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_close.png') no-repeat center center;
}
JavaScript
/* Formatting function for row details - modify as you need */
function format(d) {
// `d` is the original data object for the row
return '<div class="child-container">' +
'<table cellpadding="5" cellspacing="0" border="0">' +
'<tr>' +
'<td>Full name:</td>' +
'<td>' + d.name + '</td>' +
'</tr>' +
'<tr>' +
'<td>Extension number:</td>' +
'<td>' + d.extn + '</td>' +
'</tr>' +
'<tr>' +
'<td>Extra info:</td>' +
'<td>And any further details here (images etc)...</td>' +
'</tr>' +
'</table>' +
'</div>';
}
$(document).ready(function() {
var table = $('#example').DataTable({
"ajax": 'https://api.myjson.com/bins/16lp6',
"columns": [{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{
"data": "name"
},
{
"data": "position"
},
{
"data": "office"
},
{
"data": "salary"
},
{
"data": "extn",
"visible": false
}
],
"createdRow": function(row, data, dataIndex) {
if (data["position"] === "Software Engineer") {
$("td.details-control", row).removeClass("details-control");
}
},
"order": [
[1, 'asc']
]
});
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function() {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data()), 'no-padding').show();
tr.addClass('shown');
}
});
});