我想将字段 Sum 中的所有值添加到字段总计,但它不起作用
I want to add all the values in the field Sum to the field Total but it is not working
在这里,sums[i].value正在获得正确的值,但是当我想保留所有Sum的总和时,它失败了。
function calc() {
var amounts = document.getElementsByName("Amount");
var prices = document.getElementsByName("Price");
var sums = document.getElementsByName('Sum');
var tax = document.getElementsByName('Tax');
var total = document.getElementsByName('Total');
for (var i = 0; i < amounts.length; i++) {
sums[i].value = amounts[i].value * prices[i].value;
total[0].value = total[0].value + sums[i].value;
// only this line is not working
}
}
纯HTML是字符串,一直向下,var amounts = document.getElementsByName("Amount");
后跟amounts.value
意味着您现在有字符串值。由于+
也是一个字符串运算符,JavaScript 会很乐意将 "2"+"4"
变成"24",这看起来像是做数学,但错了,而实际上它根本没有做数学。
首先将所有需要为数字的值转换为数字:
var amounts = document.getElementsByName("Amount");
....
var amount = parseFloat(amounts.value); // NOW it's a number
...
将代码替换为:
for (var i = 0; i < amounts.length; i++) {
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
// only this line is not working
}
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
这应该对您有所帮助。
在加乘时删除 .value
function test()
{
var amounts = new Array();
amounts[0] = "4";
amounts[1] = "6";
amounts[2] = "10";
var prices = new Array();
prices[0] = "4";
prices[1] = "6";
prices[2] = "10";
var sums = new Array();
var total = 0;
for (var i = 0; i < amounts.length; i++) {
sums[i] = parseInt(amounts[i]) * parseInt(prices[i]);
total= parseInt(total) + parseInt(sums[i]);
// only this line is not working
//alert(total); is 152
}
}
相关文章:
- 模态上的输入/注册字段不起作用
- 单击跨度后打开文本字段不起作用
- jQuery更新文本字段不起作用
- Emberjs 车把内容绑定编辑字段不起作用
- NodeJS 套接字连接不起作用
- 引导超前指令对输入字段不起作用
- 用于验证空输入字段不起作用的 JS 函数
- Javascript表单验证部分检查空数据字段不起作用
- 为什么这个代码段不起作用
- Elm-从js更新日期输入字段不起作用
- 多个jquery日期时间作为表单字段不起作用
- 为什么这个javascript自动填充多个字段不起作用
- jQuery UI子菜单中的输入字段不起作用
- jQuery验证对输入字段不起作用
- 下一个元素的自动聚焦(autotab)对动态创建的字段不起作用
- 带startAt和endAt的orderByChild对合并字段不起作用
- onclick提交上的数据库更新字段不起作用
- 代码段不起作用
- JavaScript 显示/隐藏字段不起作用 - OnChange 不会每次都发生
- jQuery验证对两个字段不起作用