jQuery DataTables: How to expand/collapse all child rows - Regular table
Example for article at https://www.gyrocode.com/articles/jquery-datatables-how-to-expand-collapse-all-child-rows/
HTML
<link rel="stylesheet" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css">
<script src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
<table id="example" class="cell-border" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</thead>
</table>
CSS
td.details-control {
background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_close.png') no-repeat center center;
}
table tbody tr:nth-child(2n) > td {
padding: 0 !important;
border-bottom: none;
}
#exampleChild tbody tr td{
color: red;
background-color: #f5f5f5;
}
#exampleChild tbody td:first-child {
border-left: none;
}
#exampleChild tbody td:last-child {
border-right: none;
}
JavaScript
function format(data) {
var html = '';
if (data.office == 'San Francisco') {
html += '<table id="exampleChild" cellspacing="0" width="100%">';
html += '<tbody>';
html += '<tr>';
html += '<td class="td1">RE: ' + data.name + '</td>';
html += '<td class="td2">' + data.position + '</td>';
html += '<td class="td3">' + data.office + '</td>';
html += '<td class="td4">' + data.salary + '</td>';
html += '</tr>';
html += '</tbody>';
html += '</table>';
$(".td1").css("width", $("#example td:eq(0)").width());
$(".td2").css("width", $("#example td:eq(1)").width());
$(".td3").css("width", $("#example td:eq(2)").width());
$(".td4").css("width", $("#example td:eq(3)").width());
$(".td5").css("width", $("#example td:eq(4)").width());
}
return html;
}
$(document).ready(function() {
var table = $('#example').DataTable({
'ajax': 'https://api.myjson.com/bins/16lp6',
'columns': [{
'data': 'name'
},
{
'data': 'position'
},
{
'data': 'office'
},
{
'data': 'salary'
}
],
pageLength: 5,
});
setTimeout(function() {
table.rows().every(function() {
this.child(format(this.data())).show();
$(this.node()).addClass('shown');
});
}, 200);
});