Search code examples
javascriptjquerycssdatatables

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.


Solution

  • 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);