Reputation: 2183
I try to build a table which is both a JQuery treeTable and a JQuery datatable at the same time. Attention please, my problem is not about how to use it both, i can view without problem if i fill the "table".
But when i send an empty array to my treetable building code, i am getting error.
Here are problem lines:
$('#table tbody tr').each(function(){
console.log(this);
if(mytable.fnGetData(mytable.fnGetPosition(this))[4]){
console.log('in set child before');
$(this).addClass('child-of-'+mytable.fnGetData(mytable.fnGetPosition(this))[4]);
console.log('in set child after');
}
$(this).attr('id', mytable.fnGetData(mytable.fnGetPosition(this))[0]);
});
When i do not populate the table, despite my wish, the process goes through to the above loop, and
console.log(this)
prints out:
<tr class="odd"><td valign="top" colspan="4" class="dataTables_empty">No data available in table</td></tr>
So it generates error, because the row data is not an expected one.
I want to ask, what is the most elegant way to control if it is a populated "data", or an empty warning row? Is checking the "class" for "dataTables_empty" an appropriate method?
Or is there any other way to not to go through above loop if table is empty.
Upvotes: 6
Views: 51135
Reputation: 1559
Another way
var count = $("table.dTable").dataTable().fnSettings().aoData.length;
if (count == 0)
{
alert("Please enter the Data");
}else{
alert("Table contains " + count + ' rows');
}
<table class="dTable"></table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
Upvotes: 3
Reputation: 658
How know if Datatable is empty
var table = $('#idTable').DataTable();
if ( ! table.data().any() ) {
alert( 'Empty table' );
}
Upvotes: 13
Reputation: 441
You can also check if dataTable is empty using page.info() as described in this stackoverflow post. eg.
//gives the total number of filtered records
var totalDisplayRecord = $(".dTable").DataTable().page.info().recordsDisplay
(totalDisplayRecord === 0)? alert("table is empty") : alert("table is not empty");
or
//gives the total number of records in table
var totalRecords =$(".dTable").DataTable().page.info().recordsTotal;
//test if dataTable is empty
(totalRecords === 0)? alert("table is empty") : alert("table is not empty");
Upvotes: 6
Reputation: 9675
from the forum this might be what you're looking for:
table.fnSettings().aoData.length
gives You the length of data in table. So if it will be equal to 0 then there is no data.
if(table.fnSettings().aoData.length===0) {
alert('no data');
} else {
alert('data exists!');
}
Upvotes: 1