You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改jQuery代码实现foreach生成表格的每行总价自动计算

问题:实现订单表格每行自动计算总价

我正在为项目创建订单表单,通过PHP的foreach循环从数据库拉取数据生成表格。但当前的jQuery代码仅能计算表格第一行的数量与单价的乘积(总价),请告诉我如何修改代码以实现所有行的总价自动计算。

原代码

Cart.php

<form action="" method="POST">

<table class="table table-sm mb-3 text-center align-middle">
   <thead>
      <tr>
         <th>Product Name</th>
         <th>Quantity</th>
         <th>Unit Price</th>
         <th>Total Price</th>
      </tr>
   </thead>
   <tbody>
      <?php foreach($ProductTbl as $productdata){ ?>
      <tr>
         <td><?= $productdata->productname ?></td>
         <td><input class="w-25 text-center quantity" type="text" name="quantity[]" value="0"></td>
         <td><input class="w-25 text-center unitprice" type="text" name="unitprice[]" value="<?= $productdata->unitprice ?>" disabled="disabled"></td>
         <td><input class="w-25 text-center totalprice" type="text"  name="totalprice[]" value="" disabled="disabled"> €</td>
      </tr>
      <?php } ?>
   </tbody>
</table>

原Javascript代码

$(document).ready(function() {
    $('.quantity').keyup(function() {
    var quantity = $('.quantity').val();
    var unitprice = $('.unitprice').val();
    var totalprice = $('.totalprice').val();
 
    var result = quantity * unitprice;
      $('.totalprice').val(result);
    });
  });
});

解决方案

原代码的问题在于:使用$('.quantity').val()这类选择器时,只会获取第一个匹配元素的值,同时更新所有.totalprice元素,所以只能影响第一行。要实现每行独立计算,需要针对当前输入框所在的行进行操作:

修改后的Javascript代码:

$(document).ready(function() {
    // 封装单行总价计算逻辑
    function calculateRowTotal($row) {
        var quantity = parseFloat($row.find('.quantity').val()) || 0;
        var unitPrice = parseFloat($row.find('.unitprice').val()) || 0;
        var total = quantity * unitPrice;
        $row.find('.totalprice').val(total.toFixed(2)); // 保留两位小数符合价格格式
    }

    // 数量输入变化时计算当前行总价
    $('.quantity').on('keyup input', function() {
        var $currentRow = $(this).closest('tr');
        calculateRowTotal($currentRow);
    });

    // 页面加载时初始化所有行的总价
    $('tbody tr').each(function() {
        calculateRowTotal($(this));
    });
});

关键修改说明:

  • $(this):精准获取当前触发事件的数量输入框
  • .closest('tr'):锁定当前输入框所在的表格行,确保只操作当前行数据
  • .find('.unitprice'):在当前行内查找对应单价输入框,避免跨行取值错误
  • 封装计算函数:统一逻辑,既支持输入变化时计算,也支持页面初始化时批量计算
  • toFixed(2):格式化总价为两位小数,符合金额展示规范
  • 监听input事件:覆盖键盘输入、粘贴、鼠标选择等多种输入场景

内容的提问来源于stack exchange,提问作者Ahmet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:45:33