Search code examples
javascripthtmlinputsumreturn-value

how to find sum of input value in javascript


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>


Solution

  • 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>