how to find sum of input value in javascript

33 views Asked by At

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

There are 2 answers

1
Hujaakbar On BEST ANSWER

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>

0
Chetan Sonar On

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>