[英]How to multiply and Sum 2 columns of datatables using jquery? - Datatables
[英]Multiply two columns with datatables
我想乘两列数据表 。 我的桌子是这样的:
<table border="5" class="teste1" method="POST" id="table">
<thead>
<tr>
<th class="filter" style="width:42px; text-align: center; font-size: 12px">Quantidade</th>
<th class="filter" style="width:25px; text-align: center; font-size: 12px">Preço</th>
</tr>
</thead>
<tbody>
<tr>
<?php
while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {
?>
<td style="font-size: 12px"> <?php echo $rows_cursos['Quantidade']; ?></td>
<td style="font-size: 12px"> <?php echo $rows_cursos['Preco']; ?></td>
</tr>
<?php } ?>
</tbody>';
<?php
}
?>
</table>
然后,我尝试按如下方式乘以quantity * price
列:
(function ($) {$(document).ready(function () {
$('#table').dataTable({
drawCallback: function () {
var api = this.api();
$( api.table().footer() ).html(
api.column( 1 * 2 ).data().sum()
);
}
});
})(jQuery)
但这不起作用,我想在表底部的<tfoot> </ tfoot>
表中连续显示数据。 我希望这个乘法的总和总是根据过滤器返回结果。
我想,您已经用PHP脚本准备了HTML(我认为这不是最好的选择)。
但是,如果您在<tfoot>
保留了一些节点以显示总成本(例如,将其设为span#sumproduct
),则可以:
{search:'applied'}
选择器修饰符)行源数据放入具有rows().data()
和.toArray()
数组中 span#sumproduct
.text()
( footerCallback
选项): //source data const srcData = [['apple',5,3],['pear',4,2],['banana',3,1]] //datatables initialization $('#example').DataTable({ dom: 'ft', data: srcData, columns: ['item', 'qty', 'price'].map(title => ({title})), footerCallback: function(){ const sumProduct = this .api() .rows({search:'applied'}) .data() .toArray() .reduce((res,[item, qty, price]) => res += qty*price, 0); $('#sumproduct').text(sumProduct); } })
<!doctype html><html><head><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.css" /><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.js"></script></head><body><table id="example"><tfoot><tr><td colspan="3">Overall cost is: <span id="sumproduct"></span></td></tr></tfoot></table></body></html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.