1
<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.

3
  • It is not clear, is it like two different text that you considers as array or you input the values in each text as arrays? Commented Jan 7, 2020 at 3:36
  • For example, if user key in 1 in first array, and 2 in 2nd array, then the result will show 3. Commented Jan 7, 2020 at 3:38
  • You have multiple inputs with the same id value; there is no way to distinguish them. Commented Jan 7, 2020 at 3:42

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

HOLY MAMA, THANKYOU HERO!
Welcome Jt Tan :)
Can i know how to make the final result in 2 decimal places?
you can use sum.toFixed(2) to round the result but for that you need to change parseInt to parseFloat on line no 5.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.