gpt4 book ai didi

javascript - 将表中的数值相加(总和)

转载 作者:行者123 更新时间:2023-12-01 00:09:52 30 4
gpt4 key购买 nike

  • 我有数字输入

  • 数量约为 30

  • 我需要将它们全部汇总到一个字段

  • 我拥有的在下面

查看:

<table>
<tbody>
<tr>
<td><input class="days_tpu" type="number" id="sth_1"></td>
</tr>
<tr>
<td><input class="days_tpu" type="number" id="sth_2"></td>
</tr>
<tr>
<td><input class="days_tpu" type="number" id="sth_3"></td>
</tr>
</tbody>

// field in which it will add up
<tfoot>
<th><input id="id_days_tpu" type="time" type="text"></th>

</tfoot>
</table>

我尝试过:

  • 我尝试接受所有输入。

  • 并按长度计数

  • 并对它们求和

但是,这不起作用

Javascript:

const days_tpu_s = [...document.getElementsByClassName("days_tpu")];

//or

const table = document.querySelector('table');


table.sumInputs = function () {
var inputs = document.getElementsByClassName('days_tpu'),
result = document.getElementById('sum_id_days_tpu'),
sum = 0;

for (var i = 0; i < inputs.length; i++) {
var ip = inputs[i];

if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}

}

result.value = sum;
}
sumInputs();

有人有好主意吗?

最佳答案

您可以使用Array.prototype.map()要获取所有输入值,请使用 Array.prototype.reduce()将它们相加。

演示:

const days_tpu_s = [...document.getElementsByClassName("days_tpu")];
function sumInputs() {
var sum = days_tpu_s.map(i => Number(i.value)).reduce((a, c) => a + c, 0);
document.getElementById('id_days_tpu').value = sum;
}
days_tpu_s.forEach(function(el){
el.addEventListener('input', sumInputs);
});
<table>
<tbody>
<tr><td><input class="days_tpu" type="number" id="sth_1"></td></tr>
<tr><td><input class="days_tpu" type="number" id="sth_2"></td></tr>
<tr><td><input class="days_tpu" type="number" id="sth_3"></td></tr>
</tbody>

// field in which it will add up
<tfoot>
<th><input id="id_days_tpu" type="text"></th>
</tfoot>
</table>

关于javascript - 将表中的数值相加(总和),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60148604/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com