Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make invisible datatable when there is no data?

Is it possible to hide a table when it doesn't have any data(rows) inside? I'm using the query datatables plugin.

I couldn't find any option in the documentation.

like image 331
Okan Kocyigit Avatar asked Oct 10 '13 13:10

Okan Kocyigit


People also ask

How do I hide dataTable Export button if no data?

You can use JQuery to disable/enable the button based on the row count. Here's an example where the CSV export is disabled if the row count is zero. You could tie this to rowCallback option or a custom event.

How do you empty data in a dataTable?

function clear() Simply remove all rows of data from the table.


1 Answers

Despite good suggestions I think there still needs (another) answer.

  1. Using dataTables a <table> will never be empty - or :empty - since dataTables enforces you to have a <thead> and a <tbody>

  2. It is not enough to hide the <table>, you must hide the *_wrappper also - the <div> that contains the styled table, pagination, filter-box and so on.

You can take advantage of fnInitComplete :

$('#table').dataTable({
   //initialization params as usual
   fnInitComplete : function() {
      if ($(this).find('tbody tr').length<=1) {
         $(this).parent().hide();
      }
   } 
});

This will hide the dataTable and all its autogenerated content, if there is no rows holding data in <tbody>.


Update

[See comments for clarification] Then you need a completely other approach. This works in Chrome and FireFox, cant tell for IE :

Forget about fnInitComplete, use the following code instead :

var dataTable = $('#table').dataTable();

$("#table").on('DOMNodeInserted DOMNodeRemoved', function() {
  if ($(this).find('tbody tr td').first().attr('colspan')) {
    $(this).parent().hide();
  } else {
    $(this).parent().show();
  }
});

//this shows the dataTable (simplified)
dataTable.fnAddData(
    ['a','b','c','d','e']
);

//this hides it (assuming there is only one row)
dataTable.fnDeleteRow(0);
like image 131
davidkonrad Avatar answered Oct 11 '22 20:10

davidkonrad