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

JavaScript实现表格行Price*Quantity自动计算Amount求助

解决表格每行Amount自动计算乘积的问题

原代码核心问题

  • ID唯一性冲突:HTML里用id="quantity"、id="unit"、id="amount"标记输入框,一旦表格新增行,重复ID会导致JS无法精准获取元素,必须改用class来标识同类输入框。
  • 逻辑错误:原JS直接通过getElementById获取单个输入框的值,没有按行遍历对应元素;循环里试图用qty[i]访问数组,但qty只是单个字符串值,并非数组。
  • 未处理类型转换:输入框的value是字符串类型,直接相乘会得到非预期结果,需要转为数字后计算。

修正后的代码实现

第一步:调整HTML结构(改用class标记输入框)

<table class="table table-striped" id="line_item" data-togle="table" data-sort-stable="true">
  <thead>
    <tr>
      <th>Product</th>
      <th>Quantity</th>
      <th>Price Unit</th>
      <th>Amount</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr class="item-row">
      <td>
        <input class="form-control product" type="text" placeholder="Product">
      </td>
      <td>
        <input class="form-control quantity" type="number" placeholder="Quantity" oninput="calculateRowAmount(this)">
      </td>
      <td>
        <input class="form-control price-unit" type="number" placeholder="Price Unit" oninput="calculateRowAmount(this)">
      </td>
      <td>
        <input class="form-control amount" type="number" placeholder="Amount" readonly>
      </td>
      <td>
        <button class="btn btn-danger btn-sm" aria-label="Delete" onclick="deleteItem(this)">
          <i class="fas fa-trash"></i>
        </button>
      </td>
    </tr>
  </tbody>
</table>

第二步:编写修正后的JavaScript逻辑

// 计算单行的Amount值
function calculateRowAmount(inputElement) {
  // 获取当前输入框所在的表格行
  const row = inputElement.closest('.item-row');
  
  // 获取当前行的Quantity和Price Unit值,转为数字(空输入时默认0避免NaN)
  const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
  const priceUnit = parseFloat(row.querySelector('.price-unit').value) || 0;
  
  // 计算乘积并赋值给Amount输入框,保留两位小数可选
  const amount = quantity * priceUnit;
  row.querySelector('.amount').value = amount.toFixed(2);
}

// 删除行函数(适配多行扩展场景)
function deleteItem(btnElement) {
  const row = btnElement.closest('.item-row');
  row.remove();
}

关键改进说明

  • 按行精准计算:通过closest('.item-row')定位当前输入框所在行,确保只计算当前行的数值,不会干扰其他行。
  • 容错处理:用parseFloat转换输入值,配合|| 0处理空输入的情况,避免出现NaN。
  • 实时计算:把onblur改为oninput,输入过程中实时更新结果,提升用户体验。
  • 支持多行扩展:改用class标记元素后,新增行只需复制.item-row结构,无需修改JS逻辑。

内容的提问来源于stack exchange,提问作者Bimo Anugrah Prasetyo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 11:28:23