duanjue6575 2013-07-24 05:47
浏览 14

在jQuery中删除一个项后计算一个动态表的总和

I have a dynamic table generated by PHP code:

   $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>';

When the user click on the image to Delete one item, it calls jQuery function:

<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>

The HTML output:

<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>

It is working very good. The only thing missing and that I can't get through is how to calculate the $grand_total variable automatically without refresh the whole page right after the item is erased.

  • 写回答

2条回答 默认 最新

  • douci2516 2013-07-24 05:53
    关注

    Change this line

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

    to

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

    And change

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

    to

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

    And call the following function after the deletion is successful:

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

    I haven't tested it, but it should work.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类