我使用的是Grocery CRUD 2.0.1和Code Igniter 4.5.1下的DataTables主题
生成的表在每列的底部都有一个自动过滤器,根据使用的关键字,显示的行会被动态过滤。
我有一个列(Total),我想计算所有显示(过滤)结果的总和,并将其显示在特定的div中。
我尝试了很多方法,但我想不出实现它的方法。
我在datatables.js文件中使用了以下代码
$(document).ready(function() {
console.log("Script running!");
function calculateGrandTotal(table) {
console.log("table:", table); // Log the table object
var totalElements = table.column('.total').data().toArray(); // Get data from "total" column
if (!totalElements) {
console.error("Could not calculate totalElements!");
return;
}
console.log("totalElements:", totalElements); // Log the data array
var grandTotal = 0;
for (var i = 0; i < totalElements.length; i++) {
var price = parseFloat(totalElements[i]);
grandTotal += price;
}
return grandTotal.toFixed(2);
}
var grandTotalElement = document.getElementById("grand-total-display"); //The div id in the View
var table = $('.groceryCrudTable').DataTable; // Get DataTable instance from the event target
if (table) {
console.log("DataTable instance found!");
grandTotalElement.textContent = "Grand Total: " + calculateGrandTotal(table) + " DA";
} else {
console.error("DataTables not found on the table!");
}
});
然后控制台返回以下内容:
这是我在尝试、修补和到处寻找后能得到的最接近的结果。
初始化的DataTable实例似乎无法识别列方法,我也不知道如何达到这些列值以求和。为了获得信息,我能够在控制器中使用以下代码将一个名为.total的特定css类分配给我的目标列:
$crud->callbackColumn('Total', function ($value, $row) {return "<p class=\"total\">$value</p>";
但如果你有更好的主意,我会洗耳恭听的。
Grocery CRUD 2.0.1使用的DataTables版本似乎也不是最新的(我认为是1.9.2),所以我发现的许多建议想法都没有应用或导致不兼容问题,或者可能只是我。。。
如果杂货店CRUD和Javascript方面的任何专家能够提供帮助,我将不胜感激。
编辑:
在尝试了@Rohit和@Death这两个在我的环境中没有成功的真实答案后,以下是我的脚本的最后一个状态:
var table = $('.groceryCrudTable').DataTable();
if (table) {
console.log("DataTable instance found!");
console.log("table:", table); // Log the table object
} else {
console.error("DataTables not found on the table!");
}
$('.groceryCrudTable').DataTable({
bRetrieve: true, // I added this in reaction to the below screenshot
"footerCallback": function() {
var api = this.api(),
total = api
.column(6)
.data()
.reduce(function(a, b) {
return parseInt(a) + parseInt(b);
}, 0).toFixed(2);
console.log("Total is:", total);
$('#grand-total-display').val(total);
}
});
在我添加bRetrieve功能之前,出现了以下屏幕截图:
我认为其中一个问题是大多数人用来解决我的问题的最新版本DataTables(2.0.7)与最新Grocery CRUD迭代使用的版本(1.9.2)之间的主要区别。还有整个CodeIgniter环境、加载的javascript库、jquery和css文件,这些都使事情变得更加复杂。
除了发送一个要测试的应用程序的zip之外,我看不出有什么方法可以解决这个问题。