php - jQuery 中删除一项后计算一张动态表的总和

标签 php jquery mysql

我有一个由 PHP 代码生成的动态表:

   $grand_total=0;
   $sql1=mysql_query("SELECT * FROM cart")
   while($row=mysql_fetch_array($sql1)){

      $id=$row['id'];
      $unit_price=$row['unit_price'];
      $qty=$row['qty'];

      $total_price=$unit_price*$qty;
      $grand_total=$grand_total+$total_price;

      $output .='<tr id="$id">';
      $output .='<td>'.$unit_price.'</td>';
      $output .='<td>'.$qty.'</td>';
      $output .='<td>'.$total_price.'</td>';
      $output .='<td align="center"><img class="delete" src="images/Erase.png" alt="" width="16" height="16" rel="'.$total_price.'" /></td>';
      $output .='</tr>';

   }
   $output .='<tr>';
   $output .='<td colspan="2"> TOTAL </td>';
   $output .='<td>'.$grand_total.'</td'>;
   $output .='</tr>';

当用户点击图像删除一项时,它会调用 jQuery 函数:

<script>
$(document).ready(function(){   
    $('#table2 td img.delete').click(function(){
        if (confirm("Do you want to delete this item?")) {

          var parent = $(this).closest('TR');
          var id = parent.attr('id');
          $.ajax({
            type: "POST",
            data: "id=" +id,
            url: "packages_cart_delete.php"
          });
    $(this).parent().parent().remove();
    alert("Item has been deleted!");
}
return false;

    });
});

</script>

HTML 输出:

<table id="table2" width="100%" border="0" cellspacing="3" cellspadding="3">
   <tr>
      <th>Unit Price</th>
      <th>Qty</th>
      <th>Total Price</th>
      <th>Delete</th>
  </tr>
  <?php echo $output; ?>
</table>

它运行得非常好。唯一缺少且我无法解决的问题是如何自动计算 $grand_total 变量,而无需在删除项目后立即刷新整个页面。

最佳答案

更改此行

      $output .='<td>'.$total_price.'</td>';

      $output .='<td class="total-price">'.$total_price.'</td>';

并改变

   $output .='<td>'.$grand_total.'</td'>;

   $output .='<td class="grand-total">'.$grand_total.'</td'>;

并在删除成功后调用以下函数:

function calculateTotal() {
    var grandTotal = 0;
    $(".total-price").each( function() {
        var thisPrice = parseInt( $(this).text() );
        grandTotal += thisPrice;
    });
    $(".grand-total").text( grandTotal );
}

我还没有测试过,但它应该可以工作。

关于php - jQuery 中删除一项后计算一张动态表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17826114/

相关文章:

jquery - 无法使用 [] 验证复选框

mysql - 创建表Mysql集群问题

php - 如何修复 "Cannot add or update a child row: a foreign key constraint fails"

php - MySQL数据库-查询仅更新某些字段

php - 避免在 strtotime 为 false 时显示 1970-01-01

PHP DOMDocument 未删除所有元素

php - 可以选择第一个非空值或第一个整数值的mysql语句

php - Laravel 中的 Bootstrap 模态验证

jquery-ui - 在表格单元格内存储和访问 div 的数据

javascript - Jquery向后树遍历