发布于2021-12-03 00:25 阅读(864) 评论(0) 点赞(17) 收藏(5)
我正在从数据库中提取记录,将它们显示在带有表单输入字段的表行中。这意味着会有多行,如下面的示例 html 代码所示。我只想使用 javascript。这个想法是,当用户输入数量时,它会乘以单价,结果显示在小计字段中。我不是 JS 开发人员,我搜索并找到了接近我需要的代码。如果有人可以提出一些建议以使此代码正常工作,我将不胜感激。
<SCRIPT language="JavaScript">
<!--
function calculate() {
var Quantity = document.getElementsByName("Quantity").value;
var unitPrice = document.getElementsByName("unitPrice").value;
var total = 0;
for (var i = 0; i < Quantity.length; i++) {
total += parseInt(Quantity[i].value) * parseInt(unitPrice[i]);
}
document.getElementsByName("subtotal").value = total;
}
</SCRIPT>
<table>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2"/>
<input name="subtotal" size="2"/>
</td>
</tr>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2"/>
<input name="subtotal" size="2"/>
</td>
</tr>
</table>
一些事情:a)document.getElementsByName("")
返回元素的 NodeList 集合,因此您无法像这样获取每个输入的值,您必须将它们放入 for 循环中;b) 然后您还需要unitPrice[i]
在解析之前获取循环内每个的值,并且 c) 每次迭代后都应重置总数,因此可以将其放在循环内。见下文:
function calculate() {
var Quantity = document.getElementsByName("Quantity");
var unitPrice = document.getElementsByName("unitPrice");
for (var i = 0; i < Quantity.length; i++) {
if (!Quantity[i].value) continue; // prevent NaN
let total = parseInt(Quantity[i].value) * parseInt(unitPrice[i].value);
document.getElementsByName("subtotal")[i].value = total;
}
}
<table>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2" />
<input name="subtotal" size="2" />
</td>
</tr>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2" />
<input name="subtotal" size="2" />
</td>
</tr>
</table>
为了避免得到NaN
没有任何值的结果,您可以添加if (!Quantity[i].value) continue;
作为 for 循环中的第一行,这应该可以防止它。
作者:黑洞官方问答小能手
链接:http://www.qianduanheidong.com/blog/article/246452/2fc960070bf6c061643f/
来源:前端黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 前端黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-3
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!