You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何计算DataTable表格中TR列的平均值?

Calculating Average of TR Column in DataTable

Hey there! To calculate the average of your TR column, you can use DataTables' drawCallback function—this runs every time the table is redrawn (including after your AJAX data loads), making it perfect for computing dynamic values like averages. Here's how to modify your existing code:

table = $("#beyannameTable").DataTable( { 
    dom: 'Bfrtip', 
    buttons: ['excel', 'print'], 
    lengthChange: false, 
    searching: false, 
    paging: false, 
    "ajax": { 
        "url": "/Raporlama/ITH_Operasyon", 
        "type": "GET", 
        "datatype": "json", 
        data: { 
            tescilTrh1: $("#tescilTrh1").val(), 
            tescilTrh2: $("#tescilTrh2").val() 
        }, 
    }, 
    "columns": [ 
        { "data": "Kullanici" }, 
        { "data": "Ref" }, 
        { "data": "Tescil_No" }, 
        { "data": "UNVAN" }, 
        { "data": "TescilTarihi" }, 
        { "data": "GumrukAdi" }, 
        { "data": "Cekildi_Tarih" }, 
        { "data": "GumrukEvraklar_Tarih" }, 
        { "data": "TR" } 
    ],
    // Add this drawCallback to compute and display the average
    "drawCallback": function(settings) {
        const api = this.api();
        let total = 0;
        let validCount = 0;

        // Loop through all values in the TR column (index 8, since columns are 0-based)
        api.column(8, { page: 'current' }).data().each(function(value) {
            const numericValue = parseFloat(value);
            // Only include valid numbers in the calculation
            if (!isNaN(numericValue)) {
                total += numericValue;
                validCount++;
            }
        });

        // Calculate average (handle division by zero if no valid rows)
        const average = validCount > 0 ? (total / validCount).toFixed(2) : "N/A";

        // Display the average in the table footer
        // First, check if the footer exists—create it if not
        let footer = $("#beyannameTable tfoot");
        if (footer.length === 0) {
            footer = $('<tfoot><tr><td colspan="8" style="text-align:right;">Average:</td><td>' + average + '</td></tr></tfoot>');
            $("#beyannameTable").append(footer);
        } else {
            // Update the existing footer cell with the new average
            footer.find("td:last").text(average);
        }
    }
});

Key Details:

  • drawCallback: This function triggers after every table draw, so it will recalculate the average whenever your AJAX data loads or the table updates.
  • Column Index: The TR column is the 9th column in your setup, so we use index 8 (since DataTables uses 0-based indexing).
  • Valid Number Check: We use parseFloat to convert the TR values to numbers, and skip any non-numeric values to avoid breaking the calculation.
  • Footer Handling: The code checks if a footer exists—if not, it creates one with a cell spanning the first 8 columns (labeled "Average") and the average value in the TR column's footer cell. If the footer already exists, it just updates the value.

If you prefer to have the footer in your HTML from the start (instead of creating it dynamically), add this to your table:

<table id="beyannameTable">
    <!-- Your thead and tbody here -->
    <tfoot>
        <tr>
            <td colspan="8" style="text-align:right;">Average:</td>
            <td></td>
        </tr>
    </tfoot>
</table>

Then you can simplify the drawCallback by removing the footer creation logic—just update the last <td>'s text.

内容的提问来源于stack exchange,提问作者Gözde Yıldız

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:22:23