如何在无预定义tfoot的jQuery DataTable中添加footerCallback实现列求和?
No worries! Since you don’t have a pre-defined <tfoot> in your HTML, we can dynamically create it right within your DataTables initialization code. Here’s a straightforward solution tailored to your setup:
Step 1: Dynamically Generate the Footer
We’ll create the footer row automatically when the table finishes initializing. This ensures it matches the number of columns in your table, even if your column setup changes later.
Step 2: Implement the Footer Callback for Summation
Once the footer exists, we’ll use the footerCallback option to calculate and display the sum of the OrderTotalAmount column.
Here’s the full working code example:
$('#tblCollection').DataTable({ ajax: { url: 'your-ajax-endpoint-url', // Replace with your actual API URL type: 'GET', // Adjust to POST if needed dataSrc: '' // Modify if your response nests data under a property like "data" }, columns: [ // Your existing column definitions (example below) { data: 'OrderId', title: 'Order ID' }, { data: 'CustomerName', title: 'Customer' }, { data: 'OrderTotalAmount', title: 'Total Amount', className: 'text-right' } // Add other columns as needed ], initComplete: function(settings, json) { const api = this.api(); const footerRow = $('<tr></tr>'); // Add empty cells for every column in the table api.columns().every(function() { footerRow.append('<td></td>'); }); // Append the footer row to the table (creates <tfoot> if it doesn't exist) $(api.table().footer()).append(footerRow); }, footerCallback: function(row, data, start, end, display) { const api = this.api(); // Calculate sum of OrderTotalAmount column const sum = api.column('OrderTotalAmount:name', { page: 'current' }) .data() .reduce((acc, curr) => parseFloat(acc) + parseFloat(curr), 0); // Display sum in the corresponding footer cell // Replace index 2 with the actual column index of OrderTotalAmount $(api.column(2).footer()).html(`Total: $${sum.toFixed(2)}`); } });
Key Details to Adjust:
- Column Targeting: Use either the column index (e.g.,
column(2)) or the column name (if you define anameproperty in your columns config, likecolumn('OrderTotalAmount:name')) to target the correct column for summation. - Sum Scope: The
{ page: 'current' }option calculates the sum only for the current page. Remove this if you want the sum of all data across all pages. - Formatting:
toFixed(2)ensures currency-like formatting—adjust the number of decimal places as needed for your use case. - AJAX Setup: Double-check your
ajaxsettings match your API’s endpoint and response structure.
This approach will dynamically create the footer when the table loads, then automatically compute and display the sum of your OrderTotalAmount column.
内容的提问来源于stack exchange,提问作者weeraa

