程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

使用java脚本动态地乘以2个单元格并在第三个单元格中显示结果

发布于2021-12-03 00:25     阅读(811)     评论(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/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

17 0
收藏该文
已收藏

评论内容:(最多支持255个字符)