skip to Main Content

Can anyone help me to find sum of input values using JavaScript. The HTML and JavaScript is given below. Thanks in advance

let inputs=document.getElementsByTagName('input');
let button=document.querySelector('button');

button.addEventListener('click',function(){
let sum='';
for(let i=0;i<inputs.length;i++){
sum+=parseInt(inputs[i].value);
}
console.log(sum);
})
<input type="text">
<input type="text">
<button>Find Sum</button>

2

Answers


  1. You are defining the sum as a string and

    When you add to sum sum+=parseInt(inputs[i].value); input value is being concatenated.

    define the sum as integer such as 0.

    Check out below code:

    let inputs=document.getElementsByTagName('input');
    let button=document.querySelector('button');
    
    button.addEventListener('click',function(){
    let sum=0;
    for(let i=0;i<inputs.length;i++){
    sum+=parseInt(inputs[i].value);
    }
    console.log(sum);
    })
    <input type="text">
    <input type="text">
    <button>Find Sum</button>
    Login or Signup to reply.
  2. function calculateSum() {
      // Get the values from the input fields
      var num1 = parseFloat(document.getElementById("num1").value);
      var num2 = parseFloat(document.getElementById("num2").value);
    
      // Check if the input is valid
      if (isNaN(num1) || isNaN(num2)) {
        alert("Please enter valid numbers.");
        return;
      }
    
      // Calculate the sum
      var sum = num1 + num2;
    
      // Display the result
      document.getElementById("result").innerText = "Sum: " + sum;
    }
    <input type="text" id="num1">
    <input type="text" id="num2">
    <button onclick="calculateSum()">Find Sum</button>
    
    <p id="result"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search