多行输入框值将添加到总和

时间:2018-05-16 06:41:15

标签: javascript

我想实现多行,从两个输入框添加值,让第三个输入获得此总和值。但现在我只实现一条线。如何设置它以实现多行?你需要添加一个遍历函数吗? 感谢

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>


<input type="text" id="num1" value="20">  
<input type="text" id="num2">  
<input type="text"  value="" id="sum">  <br>

<input type="text" id="num1" value="30">  
<input type="text" id="num2">  
<input type="text"  value="" id="sum">  <br>

<script>  
window.onload = function(){  
    var inputs = document.getElementsByTagName("input");  
    for(i=0;i<inputs.length;i++){  
        inputs[i].onblur = function(){  
            var add1 = document.getElementById("num1").value;  
            var add2 = document.getElementById("num2").value;  
            document.getElementById("sum").value = add1*1 + add2*1;  
        }  
    }  
        }  
</script>  
</body>
</html>

enter image description here

3 个答案:

答案 0 :(得分:1)

以下是确切的工作代码:

let rows = document.querySelectorAll(".row");
rows.forEach(row => {
  let input = row.querySelector("input.add");
  input.addEventListener("blur", () => {

    let val1, val2;
    if (parseInt(row.querySelector(".first").value)) {
      val1 = parseInt(row.querySelector(".first").value);
    } else {
      val1 = 0;
      // alert("Please enter some number in first field");
    }

    if (parseInt(row.querySelector(".add").value)) {
      val2 = parseInt(row.querySelector(".add").value);
    } else {
      val2 = 0;
      // alert("Please enter some number in second field");
    }

    row.querySelector(".result").value = val1 + val2;
  });
});

function sum() {
  document.getElementById("totalSum").value = parseInt(document.getElementById("result1").value) + parseInt(document.getElementById("result2").value);
}
<div class="row">
  <input class="first" value="20">
  <input class="add">
  <input id="result1" class="result">
</div>
<div class="row">
  <input class="first" value="20">
  <input class="add">
  <input id="result2" class="result">
</div>
<div class="">
  <button type="button" name="button" onClick="sum();">SUM</button>
  <input id="totalSum"></input>
</div>

答案 1 :(得分:0)

您不能两次使用相同的ID。

将3个输入字段打包为div。

循环虽然divs和孩子应该是

[0] num1

[1] num2

[3]总和

如果您还有其他问题,请询问

答案 2 :(得分:0)

它是一个字符串添加但很容易修复没有时间更多;)

let rows = document.querySelectorAll(".row");
rows.forEach(row => {
  let input = row.querySelector("input.add");
  input.addEventListener("blur", () => {
    row.querySelector(".result").value = parseInt(row.querySelector(".first").value) + parseInt(row.querySelector(".add").value);
  });
})
<div class="row">
  <input class="first" value="20">
  <input class="add">
  <input class="result">
</div>
<div class="row">
  <input class="first" value="20">
  <input class="add">
  <input class="result">
</div>