To tackle the issue of adding up independent totals in a PHP foreach loop and displaying a grand total, we need to modify the JavaScript function. Right now, the function works fine for each line, but doesn't calculate the grand total correctly. Let's figure out how to save the amounts separately and then sum them up to get the desired result. The goal is to have the grand total update dynamically whenever the quantity changes, just like the individual amounts do.
<head>
<script type="text/javascript">
function update(iteration){
var qty = document.getElementById('qty_' + iteration).value;
var price = document.getElementById('price_' + iteration).value;
price = price.substring(0, 7);
qty = parseInt(qty);
var amount = (qty * price).toFixed(2) ;
parseFloat(document.getElementById('amount_' + iteration).value = amount).toFixed(2);
var subtotal = 0;
for(var i =1; i < itemCount; i++) {
subtotal += parseFloat(document.getElementById('amount_' + i).value);
}
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total $"+parseFloat(subtotal);
}
</script>
</head>
<?php
$listitems = unserialize($row["products"]);
$i=1;
foreach($listitems as $item)
{
echo '<tr><td>'.$item["code"].'</td><td><input type="number" id="qty_'.$i.'" name="qty_'.$i.'" min="1" size="3" value="1" onChange="iteration = '.$i.'; update(iteration); " /></td>';
echo '<td><input type="hidden" name="price_'.$i.'" id="price_'.$i.'" value="';
echo $item['price'];
echo '" />';
echo $item['price'];
echo '</td><td><input type="text" name="amount_'.$i.'" id="amount_'.$i.'" size="6" readonly value="';
echo $item['price'];
echo '"/></td></tr>';
$i++;
}
?>
<div id="totalPrice"></div>