Sum up input type array and show it in output

192 views Asked by At
<html>
<body>

<input type="text" id="array[]" oninput="myFunction(this.value)">      
<input type="text" id="array[]" oninput="myFunction(this.value)">       
<p id="result"></p>

<script>
function myFunction(val) {
  document.getElementById("result").innerHTML = val; 
}
</script>

</body>
</html>

I want to add up the two array and show it in "result". But currently it will just show one. Can i know how to add the two array in javascript? For example: user input 1 + input 2, it will show 3 in bottom.

2

There are 2 answers

4
Sohail Ashraf On BEST ANSWER

Add a class attribute in the input element or use the tag selector in querySelectorAll. then loop over the input element and sum the values.

function myFunction(val) {
    const ele = document.querySelectorAll('input');
    let sum = 0;
    ele.forEach(input => {

        sum += input.value ? parseFloat(input.value) : 0;
    });
    document.getElementById('result').textContent = sum.toFixed(2);
}
    <input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
    <input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
    <p id="result"></p>

0
Anuradha On

Please check this solution.

<html>
<body>

<input type="text" id="array1" oninput="myFunction1(this.value)">      
<input type="text" id="array2" oninput="myFunction2(this.value)">       
<p id="result"></p>

<script>
var val1 = 0;
var val2 = 0;
var val3 = 0;
function myFunction1(val) {
  if (val !== "") {
    val1 = parseInt(val);
  } else {
    val1 = 0;
  }
    val3 = val1 + val2;
    document.getElementById("result").innerHTML = val3; 
  }

  function myFunction2(val) {
    if (val !== "") {
    val2 = parseInt(val);
  }  else {
    val2 = 0;
  }
    val3 = val1 + val2;
    document.getElementById("result").innerHTML = val3; 
  }


  </script>

  </body>
  </html>