Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To toggle empty data in Datatables, you can use the drawCallback function in Datatables.

First, you need to add a column containing a toggle button for each row. You can use the following code to add a column with a toggle button:

columnDefs: [
  {
    targets: -1,
    data: null,
    defaultContent: "<button>Toggle</button>"
  }
],

Next, you need to define the drawCallback function to hide or show the rows with empty data based on the toggle button click. You can use the following code:

drawCallback: function(){
  var api = this.api();
  $('button', api.table().container()).on('click', function(){
    var row = api.row($(this).parents('tr'));
    var rowData = row.data();
    var isEmpty = true;
    $.each(rowData, function(key, value){
      if(value !== null && value !== ''){
        isEmpty = false;
        return false;
      }
    });
    if(isEmpty){
      if(row.child.isShown()){
        row.child(false);
        $(this).html('Toggle');
      }
      else{
        row.child('No data available').show();
        $(this).html('Hide');
      }
    }
  });
}

This function adds an event listener to the toggle button for each row. When the button is clicked, it checks whether the row data is empty. If the row data is empty, it shows or hides the child row containing the "No data available" message. Finally, it updates the toggle button text to "Toggle" or "Hide" accordingly.