javascript - 使用 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。我将不胜感激任何帮助。谢谢!
解决方案
如前所述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>
推荐阅读
- html - 来自 Assets/img/img1.jpg 文件夹的 Angular 8 背景图像 URL 不起作用
- python - 为什么 str.split() 不适用于 fastapi str 类型?
- java - java - 如何在java中删除我的SQL结果中的空值?
- php - ESP8266 无法将数据发送到本地数据库(XAMPP)
- python - Tkinter Python 中的标签放置
- python - CNN python 的简单模型帮助
- json - Sublime 中的 .json 文件上的这些红色箭头和黄色矩形是什么?
- javascript - Angular 8 表格行渲染指令问题
- r - 如何在一个图中绘制来自不同模型的估计值
- python - 每次用户输入后如何正确显示菜单?