JavaScript forEach() Method
The forEach()
method calls the function once for each element of the array.
Syntax
var a=[1,2,3,4,5]; a.forEach(function(value,index){ console.log(value); });
The following example shows, how to sum all input values using JavaScript forEach()
method.
Example
<html> <body> <p><input type='text' class='txt'></p> <p><input type='text' class='txt'></p> <p><input type='text' class='txt'></p> <p><input type='text' class='txt'></p> <p><input type='text' class='txt'></p> <input type='button' value='Get Total' onclick='get_total()'> <p id='output'></p> <script> function get_total(){ var a=document.querySelectorAll(".txt"); var sum=0; a.forEach(function(ele){ sum+=Number(ele.value); }); document.querySelector("#output").innerText="Toatl is "+sum; } var a=[1,2,3,4,5]; a.forEach(function(value,index){ console.log(value); }); </script> </body> </html>Try it Yourself