![](/img/trans.png)
[英]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.