Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading