Wolfzmus Wolfzmus - 1 month ago 24
Javascript Question

check count datatable is empty or not

I have trouble to get count datatables, i need to chect that table is emtpy or not, this my code :

var table = $("#tbl_tmppo");
var target = table.attr('data-table');

var oTable = table.on( 'processing.dt', function ( e, settings, processing ) {
if (processing) {
$(this).find('tbody').addClass('load1 csspinner');
} else{
$(this).find('tbody').removeClass('load1 csspinner');
};
} ).DataTable({
"bServerSide": true,
"ajax": host+'datatable/'+target,
"columnDefs": [{
"targets": [ -1 ],
"className": "dt-body-left",
}]
});


i'm kinda stuck in here, i wanna check if i dont have data on Otable, i need do something, if not i need to something else. Anyone can help me??

Update :
I was using like oTable.Data().length, but it always show 0 length to me even i have 2 record on that table. if i use oTable.Data().count() is show error not undifined.

CLOSED. Tq for kcp code

oTable.on('draw', function () {
/* Now you can count rows */
var count = table.data().count()-1;


});

so i can get count my data. Tq kcp!!! U're awsome!!

kcp kcp
Answer

You can use dataFilter to get length of rows.

DataTable({
    "bServerSide": true,
    ajax: {
        url: host+'datatable/'+target,
        dataFilter: function(data){
            var json = jQuery.parseJSON( data );
            /* Here you have your results */
            json.recordsTotal = json.recordsTotal;
            json.recordsFiltered = json.recordsFiltered;
            json.data = json.list;

            return data;
        }
    }
    "columnDefs": [{
       "targets": [ -1 ],
       "className": "dt-body-left",
     }]
})

@edit: For non-backend data you can use draw event. For example:

oTable.on('draw', function () {
    /* Now you can count rows */
    var count = table.find("tr").size();
});

@edit2: You can also use data().count() method of DataTable.API

oTable.on('draw', function () {
        /* Now you can count rows */
        var count = table.data().count();
});
Comments