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
You are defining the
sum
as a string andWhen 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: