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

如何在Laravel应用中用JavaScript根据数量计算每个商品的总价?

问题解决方法

问题出在你用了重复的id属性——HTML里id是唯一标识,多个商品复用同一个id时,JS的getElementById只会获取到第一个匹配的元素,所以只有第一个商品能计算总价。

修改后的HTML结构(每个商品用独立容器包裹)

把每个商品的数量、价格、总价放在一个容器里,去掉重复的id,仅用类名区分:

<div class="item-group">
    <p>Quantity: <input type="number" onchange="totalAmount(this)" class="item_quantity" name="item_quantity[]"></p>
    <p>Item Price: AED - <span class="item_cost">{{ $lnkditem->item_cost}}</span></p>
    <p>Total Amount: AED - <strong style="color: red"><span class="item-total"></span></strong></p>
</div>
<!-- 多个商品就重复上面的.item-group容器 -->

修改后的JS代码

通过触发事件的输入框(this)定位到它所在的商品容器,再在容器内获取对应的价格和总价元素,实现每个商品独立计算:

function totalAmount(input) {
    // 获取当前输入框所属的商品组容器
    const itemGroup = input.closest('.item-group');
    // 从容器内读取数量和价格(默认值设为0避免NaN)
    const quantity = Number(input.value) || 0;
    const itemCost = Number(itemGroup.querySelector('.item_cost').textContent) || 0;
    // 计算总价并更新到当前商品的总价显示位
    const total = quantity * itemCost;
    itemGroup.querySelector('.item-total').textContent = total;
}

额外提示

  • 把name="item_quantity"改成name="item_quantity[]",这样Laravel后端能接收所有商品的数量数组。
  • 原代码里的<p type="number">是错误写法,type属性不属于<p>标签,用<span>包裹价格更合理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:54:36