DataTables - Child rows

by Guruprasad Rao

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>
<script src="//cdn.jsdelivr.net/jquery.scrollto/2.1.2/jquery.scrollTo.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th></th>
            <th>Date</th>
            <th>Supplier</th>
            <th>Total</th>
            <th>Payment</th>
        </tr>
    </thead>
    <tbody>
      
    </tbody>
</table>

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 ) {
    console.log(d.product);
    var trs='';
    $.each($(d.product),function(key,value){
    	trs+='<tr><td>'+value+'</td><td>'+d.price[key]+'</td></tr>';
    })
    // `d` is the original data object for the row
    return '<table class="table table-border table-hover">'+
           '<thead>'+
              '<th>Product</th>'+
            	'<th>Price</th>'+  
           '</thead><tbody>' +
           	
           trs+
        '</tbody></table>';
}

$(document).ready(function() {
    var table = $('#example').DataTable({
        "ajax": 'https://raw.githubusercontent.com/kshkrao3/JsonFileSample/master/Employees.json',
        "columns": [
            {
                "class":          'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },
            { "data": "date"},
            { "data": "supplier"},
            { "data": "total"},
            { "data": "payment"}
        ]
    });

    // 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()) ).show();
          tr.addClass('shown');
        }
    });
});