jQuery Datatables scroll to bottom when a row is added - javascript

I'd like my DataTable to scroll to the bottom whenever a row is added. I have tried multiple fixes for this problem, but none of them work.
Tested solutions:
How to load table in Datatables and have it scroll to last record automatically on load
Jquery DataTable auto scroll to bottom on load
Among others...
I think that what separates my case from the others, is that I am using DataTable with the D capitalized.
Anyway, here is my current code:
var table = $('#example').DataTable({
"createdRow": function( row, data, dataIndex )
{
$(row).attr('id', 'row-' + dataIndex);
},
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"bInfo": false,
"bAutoWidth": false,
"scrollY": $(window).height()/1.5,
"scrollCollapse": true,
"paging": false,
});
for(var i = 1; i <= 20; i++){
table.row.add([
i,
'action'+i,
]);
}
table.draw();
table.rowReordering();
It would be nice if the table scrolled to bottom whenever a new row is added to it..

SOLUTION
To scroll to the bottom of the table, use the code below:
var $scrollBody = $(table.table().node()).parent();
$scrollBody.scrollTop($scrollBody.get(0).scrollHeight);
DEMO
$(document).ready( function () {
var table = $('#example').DataTable({
"createdRow": function( row, data, dataIndex ) {
$(row).attr('id', 'row-' + dataIndex);
console.log($(row).closest('table').parent());
},
"scrollY": $(window).height()/1.5,
"scrollCollapse": true,
"paging": false
});
$('#btn-add').click(function(){
for(var i = 1; i <= 10; i++){
table.row.add([
i,
i + '.2',
i + '.3',
i + '.4',
i + '.5',
i + '.6'
]);
}
table.draw();
// Scroll to the bottom
var $scrollBody = $(table.table().node()).parent();
$scrollBody.scrollTop($scrollBody.get(0).scrollHeight);
});
table.rowReordering();
} );
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>jQuery DataTables</title>
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdn.rawgit.com/mpryvkin/jquery-datatables-row-reordering/95b44786cb41cf37bd3ad39e39e1d216277bd727/media/js/jquery.dataTables.rowReordering.js"></script>
</head>
<body>
<button id="btn-add" type="button">Add records</button>
<table id="example" class="display" 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>
</tbody>
</table>
</body>
</html>

Related

jQuery onClick function not trigger if the datatable collapse to responsive view on mobile

Currently I'm using datatable responsive for displaying my table, the "Edit" button work well if it showing full width, but once it goes to responsive on mobile then the button won't trigger the modal and also display.
I did try with "vclick" or " touchstart" on the onclick function but still no luck.
Here my code for the jQuery :
$( "#btnSearch" ).click(function(event){
var branch = $('#searchByBranch').val();
var startDate = $('#searchByDateFromValue').val();
var endDate = $('#searchByDateToValue').val();
event.preventDefault();
$.ajax({
type : "POST",
url: "<?php echo base_url(); ?>index.php/Manage_Sales/searchSalesByDateRange",
data : { from: startDate, to: endDate , branch : branch},
success : function(response) {
$("#searchResult").html(response);
}
}).done(function(){
var level = <?php print($sessionLevel)?>;
$("#resultTable_ReplaceCard").DataTable({
"responsive": true, "lengthChange": true, "autoWidth": true,
"lengthMenu": [
[50, 100, -1],
[50, 100, 'All'],
],
"order" : [1, 'desc'],
}).buttons().container().appendTo('#resultTable_wrapper .col-md-6:eq(0)');
//Edit Replace Card
$('.editReplaceCardBtn').on('click', function (){
$('#replaceCard_Modal').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children("td").map (function(){
return $(this).text();
}).get();
$('#replaceCard_ID').val(data[0]);
$('#replaceCard_Amount').val(data[3]);
});
});
});
My datatable code as below :
//Replace Card Tab
$result_ReplaceCard = $this->Sales_Model->getCardReplaceList($startDate, $endDate, $branch);
if($result_ReplaceCard == TRUE){
echo '
<div class = "row">
<div class= " col-12 col-sm-12">
<table id="resultTable_ReplaceCard" class="table table-bordered table-striped dataTable display" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Manage By</th>
<th>Amount</th>
<th>Datetime</th>
<th>Action</th>
</tr>
</thead>
<tbody>
';
foreach($result_ReplaceCard as $row){
//Show Result
echo "<tr>
<td>$row->id</td>
<td>$row->name</td>
<td>$row->loginUser</td>
<td>$row->amount</td>
<td>$row->rdate</td>
<td>
<button type=\"button\" class = \"btn btn-success editReplaceCardBtn\" >EDIT</button>
</td>
</tr>
";
}
echo '
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
<th>Manage By</th>
<th>Amount</th>
<th>Datetime</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
</div>
';
The edit button callback was fine when it was full width, it does not responce once it goes to responsive on mobile. Please help

Using Datatables with output as map objects

I am trying to use the below example from datatables : https://datatables.net/examples/data_sources/js_array.html , but when i am trying to retrieve data from a url as map , it is giving me error.
Below is the html code for this , i am hitting a mock api to get the object then iterating to get the object that datatable expect as input .
<html>
<head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var completeObject = {} ;
var employeeArray = [] ;
$.getJSON('https://run.mocky.io/v3/3a65891c-84c8-467e-b2e9-ecb1629e1c45', function(json_data){
$.each(json_data, function(k, v) {
var tem_arr = [] ;
tem_arr.push(v['name']);
tem_arr.push(v['position']);
tem_arr.push(v['office']);
tem_arr.push(v['extn']);
tem_arr.push(v['start_date']);
employeeArray.push(tem_arr);
});
console.log('check inner >>' + JSON.stringify(employeeArray) );
$('#example').DataTable({
data: employeeArray ,
columns: [
{ data: 'name' },
{ data: 'position' },
{ data: 'salary' },
{ data: 'office' },
{ data: 'extn' },
{ data: 'start_date' },
],
});
});
});
</script>
</head>
<body>
<div class="container">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
</tr>
</tfoot>
</table>
</div>
</body>
</html>

Populate bootstrap-select with array of options

I created a table using datatables and on footer I added anempty dropdown select using Bootstrap-select as below :
<tfoot>
<tr>
<th><select class="selectpicker" multiple></select></th>
</tr>
</tfoot>
When my datatable is created, I want to add the distinct values of that column as options in my select.
The issue is : the datatable is drawn without errors but the select is not populated. It still shows empty but when i use inspect on browser I see the options are already inside the select.
I used emptybefore append and tried html instead of append but still not showing the options. I also tried footerCallback instead of initComplete.
When I add the options manually inside my select in the html, it works fine. it looks like in datatable the footer is loaded before the body that's why it's not showing the options when it's displayed before the body is ready.
Any suggestions please how I could fixe it ? Thank you very much.
$(document).ready(function() {
$('.selectpicker').selectpicker();
$('#example').DataTable({
"lengthChange": false,
"info": false,
"paging": false,
"searching": false,
initComplete: function () {
this.api().columns().every( function () {
var column = this;
column.data().unique().sort().each( function ( d, j ) {
$('.selectpicker').append( '<option value="'+d+'">'+d+'</option>' ) } );
} ); } }); });
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/css/bootstrap-select.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/js/bootstrap-select.min.js"></script>
<table id="example" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr><td>Austria</td></tr>
<tr><td>Japan</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>Finland</td></tr>
<tr><td>India</td></tr>
<tr><td>USA</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>France</td></tr>
<tr><td>Austria</td></tr>
</tbody>
<tfoot>
<tr>
<th><select class="selectpicker" multiple></select></th>
</tr>
</tfoot>
</table>
Your mistake was initiating your selectpicker before populating it with options, whereas the opposite is recommended in their reference docs.
Following is a fixed live-demo:
$('#example').DataTable({
lengthChange: false,
info: false,
paging: false,
searching: false,
initComplete: function(){
const table = this.api();
table.columns().every(function(){
const title = $(this.header()).text();
const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '');
$('.selectpicker').append(options).selectpicker()
});
}
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" /><link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet" /><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/css/bootstrap-select.min.css"><script src="https://code.jquery.com/jquery-3.5.1.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script><script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script><script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/js/bootstrap-select.min.js"></script><table id="example" class="table table-bordered" style="width:100%"><thead><tr><th>Country</th></tr></thead><tbody><tr><td>Austria</td></tr><tr><td>Japan</td></tr><tr><td>Sweden</td></tr><tr><td>Finland</td></tr><tr><td>India</td></tr><tr><td>USA</td></tr><tr><td>Sweden</td></tr><tr><td>France</td></tr><tr><td>Austria</td></tr></tbody><tfoot><tr><th><select class="selectpicker" multiple></select></th></tr></tfoot></table>
You will need to initialize the selectpicker after you append the data not before.
$(document).ready(function() {
$('#example').DataTable({
"lengthChange": false,
"info": false,
"paging": false,
"searching": false,
initComplete: function () {
this.api().columns().every( function () {
var column = this;
column.data().unique().sort().each( function ( d, j ) {
$('.selectpicker').append( '<option value="'+d+'">'+d+'</option>' ) } );
} ); } });
// initialize the selectpicker after appending options
$('.selectpicker').selectpicker();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/css/bootstrap-select.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/js/bootstrap-select.min.js"></script>
<table id="example" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr><td>Austria</td></tr>
<tr><td>Japan</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>Finland</td></tr>
<tr><td>India</td></tr>
<tr><td>USA</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>France</td></tr>
<tr><td>Austria</td></tr>
</tbody>
<tfoot>
<tr>
<th><select class="selectpicker" multiple></select></th>
</tr>
</tfoot>
</table>

Expand/Collapse all with Nested Table - jQuery Datatables

I am using datatables plugin. I would like to ask, is there any way to expand/collapse all rows of the nested table. I tried to implement this below, but it doesn't work. I would like to expand/collapse rows like this example
https://www.gyrocode.com/articles/jquery-datatables-how-to-expand-collapse-all-child-rows/#regular.
Please help thanks
function fnFormatDetails(table_id, html) {
var sOut = "<table id=\"exampleTable_" + table_id + "\">";
sOut += html;
sOut += "</table>";
return sOut;
}
var iTableCounter = 1;
var oTable;
var oInnerTable;
var TableHtml;
//Run On HTML Build
$(document).ready(function () {
TableHtml = $('#exampleTable_2').html();
//Insert a 'details' column to the table
var nCloneTh = document.createElement('th');
var nCloneTd = document.createElement('td');
nCloneTd.innerHTML = '<img src="http://i.imgur.com/SD7Dz.png">';
nCloneTd.className = "center";
$('#exampleTable thead tr').each(function () {
this.insertBefore(nCloneTh, this.childNodes[0]);
});
$('#exampleTable tbody tr').each(function () {
this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);
});
//Initialse DataTables, with no sorting on the 'details' column
var oTable = $('#exampleTable').dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers',
'aoColumnDefs': [{
'bSortable': false,
'class': 'details-control',
'aTargets': [0]
}
],
'aaSorting': [[1, 'asc']]
});
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('#exampleTable tbody tr img').on('click', function () {
var nTr = $(this).closest('tr');
if (oTable.fnIsOpen(nTr)) {
/* This row is already open - close it */
this.src = "http://i.imgur.com/SD7Dz.png";
oTable.fnClose(nTr);
} else {
/* Open this row */
this.src = "http://i.imgur.com/d4ICC.png";
oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
oInnerTable = $('#exampleTable_' + iTableCounter).dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers'
});
iTableCounter = iTableCounter + 1;
}
$('#btn-show-all-children').on('click', function () {
// Enumerate all rows
oTable.rows().every(function () {
// If row has details collapsed
if (!this.oTable.fnIsOpen(nTr)) {
/* Open this row */
this.src = "http://i.imgur.com/d4ICC.png";
this.oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
this.oInnerTable = $("#exampleTable_" + iTableCounter).dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers'
});
iTableCounter = iTableCounter + 1;
}
});
});
// Handle click on "Collapse All" button
$('#btn-hide-all-children').on('click', function () {
// Enumerate all rows
oTable.rows().every(function () {
// If row has details expanded
if (oTable.fnIsOpen(nTr)) {
/* This row is already open - close it */
this.src = "http://i.imgur.com/SD7Dz.png";
oTable.fnClose(nTr);
}
});
});
$('#btn-show-all-children').on('click', function () {
// Enumerate all rows
oTable.rows().every(function () {
// If row has details collapsed
if (!this.oTable.fnIsOpen(nTr)) {
/* Open this row */
this.src = "http://i.imgur.com/d4ICC.png";
this.oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
this.oInnerTable = $("#exampleTable_" + iTableCounter).dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers'
});
iTableCounter = iTableCounter + 1;
}
});
});
// Handle click on "Collapse All" button
$('#btn-hide-all-children').on('click', function () {
// Enumerate all rows
oTable.rows().every(function () {
// If row has details expanded
if (oTable.fnIsOpen(nTr)) {
/* This row is already open - close it */
this.src = "http://i.imgur.com/SD7Dz.png";
oTable.fnClose(nTr);
}
});
});
});
});
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;
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
<link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<!-- Col reorder with resize-->
<script src="colreorderwithresize.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
</head>
<body>
<button id="btn-show-all-children" type="button">Expand All</button>
<button id="btn-show-all-children" type="button">Collapse All</button>
<table id="exampleTable">
<thead>
<tr>
<th>Year</th>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>2012</td>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<div style="display:none">
<table id="exampleTable_2" class="display select" width="100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody >
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
<td>5421</td>
<td>t.nixon#datatables.net</td>
</tr>
<tr>
<td>Garrett</td>
<td>Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
<td>8422</td>
<td>g.winters#datatables.net</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
PROBLEM
There are too many issues with the code to list them all. For example:
Multiple versions of jQuery DataTables included - 1.9 and 1.10
Multiple versions of jQuery included: 1.11 and 3.5
DataTables 1.10 API method such as rows() are called on DataTables 1.9 instance, see API for more details.
Event handlers are assigned multiple times in incorrect places.
SOLUTION
Please see below the corrected code and adjust to the libraries that you're using.
function fnFormatDetails(table_id, html) {
var sOut = "<table id=\"exampleTable_" + table_id + "\">";
sOut += html;
sOut += "</table>";
return sOut;
}
var iTableCounter = 1;
var oTable;
var oInnerTable;
var TableHtml;
//Run On HTML Build
$(document).ready(function () {
TableHtml = $('#exampleTable_2').html();
//Insert a 'details' column to the table
var nCloneTh = document.createElement('th');
var nCloneTd = document.createElement('td');
$('#exampleTable thead tr').each(function () {
this.insertBefore(nCloneTh, this.childNodes[0]);
});
//Initialse DataTables, with no sorting on the 'details' column
var oTable = $('#exampleTable').dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers',
'aoColumnDefs': [{
'bSortable': false,
'class': 'details-control',
'aTargets': [0]
}
],
'aaSorting': [[1, 'asc']]
});
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('#exampleTable tbody tr td.details-control').on('click', function () {
var nTr = $(this).closest('tr');
if (oTable.fnIsOpen(nTr)) {
oTable.fnClose(nTr);
} else {
oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
oInnerTable = $('#exampleTable_' + iTableCounter).dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers'
});
iTableCounter = iTableCounter + 1;
}
});
// Handle click on "Collapse All" button
$('#btn-hide-all-children').on('click', function () {
// Enumerate all rows
oTable.$('tr').each(function(index, nTr){
// If row has details expanded
if (oTable.fnIsOpen(nTr)) {
oTable.fnClose(nTr);
$(nTr).removeClass('shown');
}
});
});
$('#btn-show-all-children').on('click', function () {
// Enumerate all rows
oTable.$('tr').each(function(index, nTr){
// If row has details collapsed
if (!oTable.fnIsOpen(nTr)) {
/* Open this row */
oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
$(nTr).addClass('shown');
}
});
});
});
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;
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.21/datatables.min.css">
<script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<!-- Col reorder with resize-->
<script src="colreorderwithresize.js"></script>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.21/datatables.min.js"></script>
</head>
<body>
<button id="btn-show-all-children" type="button">Expand All</button>
<button id="btn-hide-all-children" type="button">Collapse All</button>
<table id="exampleTable" class="display">
<thead>
<tr>
<th>Year</th>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>2012</td>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td></td>
<td>2012</td>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<div style="display:none">
<table id="exampleTable_2" class="display select" width="100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody >
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
<td>5421</td>
<td>t.nixon#datatables.net</td>
</tr>
<tr>
<td>Garrett</td>
<td>Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
<td>8422</td>
<td>g.winters#datatables.net</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
LINK
Please see jQuery DataTables: How to expand/collapse all child rows for more information and examples.

How to add id in TD tag?

I'm using DataTables plugins (I'm a beginner) and I would like to add an 'id' in the <td> HTML tag. I did what's in this post but it's not what I want.
I saw this post too but I don't know how to use this code.
JS :
$('#datatable').dataTable({
"sPaginationType" : "full_numbers",
"createdRow" : function ( row, data_use, dataIndex ) {
$(row).attr('id', dataIndex);
},
data : data_use,
columns : column_name,
dom : 'Bfrtip',
select : 'single',
responsive : true,
altEditor : true,
destroy : true,
searching: true,
buttons : [{
extend : 'selected',
text : 'Edit',
name : 'edit'
}],
});
You can do this by adding a columnDefs array to your DataTable configuration and adding a createdCell function. For example:
$(document).ready(function() {
var table = $('#example').DataTable({
'columnDefs': [{
'targets': "_all", // this will invoke the below function on all cells
'createdCell': function(td, cellData, rowData, row, col) {
// this will give each cell an ID
$(td).attr('id', 'cell-' + cellData);
}
}]
});
Run the snippet below to see a complete example. You can right click on a cell (i.e., a td) and click "Inspect" to see the id attribute that is added to each cell.
$(document).ready(function() {
var table = $('#example').DataTable({
'columnDefs': [{
'targets': "_all",
'createdCell': function(td, cellData, rowData, row, col) {
$(td).attr('id', 'cell-' + cellData);
}
}]
});
// Add some data to the table
table.row.add(['Airi Satou', 'Accountant', 'Tokyo', '5407', '2008/11/28', '$162,700']).draw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>
<link href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css" rel="stylesheet" />
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>

Categories