Sum items in a table by class

HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>sum table items using class</title> </head> <body> <form> <table> <tbody> <tr> <td><input type="number" value="50" class="preco"></td> </tr> <tr> <td><input type="number" value="150" class="preco"></td> </tr> <tr> <td><input type="number" value="250" class="preco"></td> </tr> <tr> <td><input type="number" value="660" class="preco"></td> </tr> <tr> <td><input type="number" value="20" class="preco"></td> </tr> </tbody> </table> <input type="button" id="soma" value="OK"/> </form> <div></div> </body> </html>
CSS
div { color: red; }
JAVASCRIPT
$(document).ready(function() { return $('#soma').click(function(event) { var sum; sum = 0; $('.preco').each(function() { var value; value = Number($(this).val()); console.log(value); if (!isNaN(value) && value.length !== 0) { sum += parseFloat(value); } }); console.log(sum); }); });
Expand for more options Login