首页 > 解决方案 > 使用 Jquery 添加多个输入不起作用

问题描述

我有一个简单的问题,我可能只是没有考虑清楚。我正在尝试将几个输入字段加在一起(它们都是格式化的数字,如 2.00、3.00 等)。

但使用以下脚本:

 var sum = parseFloat(0).toFixed(2);
    //using an iterator find and sum the values of checked checkboxes
    $(".amountCheckbox:checked").each(function() {
        var input = parseFloat($(this).closest('tr').find('.amountInput').val());
        console.log(input.toFixed(2));
      sum += input.toFixed(2);
      console.log(sum);
    });
    return sum;

它返回 02.003.00 而不是 5.00。我将不胜感激任何帮助。谢谢!

标签: javascriptjquery

解决方案


如前所述Number.toFixed(),返回一个字符串,因此+连接而不是添加数字。Array#reduce()试试这个方法:

return $(".amountCheckbox:checked").closest('tr').find('.amountInput')
.map((index,input) => +input.value).get()
.reduce((acc, cur) => acc + cur, 0);

演示

$(':checkbox').on('change', function() {
    const sum = $(".amountCheckbox:checked")
    .closest('tr').find('.amountInput')
    .map((index,input) => +input.value).get()
    .reduce((acc, cur) => acc + cur, 0);
    
    console.log( sum.toFixed(2) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>Row 1</td>
      <td><input type="text" class="amountInput" value="2.00"></td>
      <td><input type="checkbox" class="amountCheckbox"></td>
    </tr>
    <tr>
      <td>Row 2</td>
      <td><input type="text" class="amountInput" value="5.00"></td>
      <td><input type="checkbox" class="amountCheckbox"></td>
    </tr>
    <tr>
      <td>Row 3</td>
      <td><input type="text" class="amountInput" value="1.00"></td>
      <td><input type="checkbox" class="amountCheckbox"></td>
    </tr>
    <tr>
      <td>Row 4</td>
      <td><input type="text" class="amountInput" value="2.20"></td>
      <td><input type="checkbox" class="amountCheckbox"></td>
    </tr>
  </tbody>
</table>


推荐阅读