如何计算小计部分中所有价格的总计?

时间:2019-08-07 18:35:26

标签: javascript php html css ajax

有一个具有数量价格和小计的产品表,我只想计算所有小计的总和,并在大计部分中显示,小计价格在类名称为“总计”的部分中。我试图汇总所有小计价格,但结果在大计部分显示“ 0.00”。表格如下:
here is the table look like

代码:

<?php

include("includes/db.php");

$object   = $_GET['dist'];
$items = json_decode(($object), true); 
$itemIds = [];
foreach( $items as $item){
    $itemIds[] = $item["id"];
}
$idstr = implode(" ,", $itemIds);
$query = "SELECT id, product_title as name ,price FROM products WHERE id IN ($idstr)";

$result = mysqli_query($conn,$query) ;
echo "<table>";
echo "<tr><th>Name</th><th>Price</th><th>Quantity</th><th>Sub Total</th></tr>";
while($row = mysqli_fetch_assoc($result)){
echo "<tr> ";
    echo "<td>" .  $row["name"] . "</td>";
    echo "<td>" .  $row["price"] . "</td>";
    $quantity = null;
    $subtotal = null;
    foreach($items as $key => $item){
        if($item["id"] == $row["id"]){
            $quantity = $item["quantity"];
            $subtotal = $quantity * $row["price"];
            $items[$key]["price"] = $row["price"];
            $items[$key]["subtotal"] = $subtotal;
        }
    }
    echo "<td>" . $quantity . "</td>";
    echo "<td class='total'>" .  $subtotal . "</td>";
    echo "</tr> ";
}
echo "</table>";
echo "<h2 id='grandtotal'></h2>";
?>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// // Grand Total
function grandtotal() {

var sum=0;
$('td.total').each(function(){
var item_val=parseFloat($(this).val());
if(isNaN(item_val)){
  item_val=0;
}
sum+=item_val;
console.log(sum);
$('h2#grandtotal').text(sum.toFixed(2));
});

}
</script>

0 个答案:

没有答案