I have developed a code in shiny R to generate a data table that expands to display child rows when a row is clicked. However, the expansion feature is only working for the last row of the table. For all previous rows, only the headers of the child table are being displayed without any data.
Here is my data table for reference: Data Table
And here is the output I am currently getting: My result
callback = JS("table.column(1).nodes().to$().css({cursor: 'pointer'});
// Formatting the cars object into another table
var format = function (d) {
if (d != null) {
var result = ('<table id=\"child_' + d[2] + '_' + d[3] +
'\">').replace('.', '_') + '<thead><tr>'
for (var col in d[4][0]) {
result += '<th>' + col + '</th>'
}
result += '</tr></thead></table>'
return result
} else {
return '';
}
}
var format_datatable = function (d) {
var dataset = [];
for (i = 0; i <= d[4].length - 1; i++) {
var datarow = $.map(d[4][i], function (value, index) {
return [value];
});
dataset.push(datarow)
}
var subtable = $(('table#child_' + d[2] + '_' +
d[3]).replace('.', '_')).DataTable({
'data': dataset,
'autoWidth': true,
'deferRender': true,
'info': false,
'lengthChange': false,
'ordering': true,
'paging': false,
'scrollX': false,
'scrollY': false,
'searching': false
});
};
table.on('click', 'td.details-control', function () {
var td = $(this),
row = table.row(td.closest('tr'));
if (row.child.isShown()) {
row.child.hide();
td.html('⊕');
} else {
row.child(format(row.data())).show();
td.html('⊖');
format_datatable(row.data())
}
});
")