How do I sum up several columns with javascript and jQuery?

mrc

New Member
I have a table with two different columns that I would like to add up to their respective sums. Right now I just add up one of the columns, I could add up the second column by just making the same JS again but with different names for the values but that is not so pretty.How would I do to change it so it counts the ue column as well as the egen and spit out two results, sum and sum2.\[code\]<table> <tr> <td><asp:TextBox ID="TextBox1" runat="server">Number</asp:TextBox></td> <td class="egen"><asp:TextBox ID="TextBox56" runat="server" Columns="1">56</asp:TextBox></td> <td class="ue"><asp:TextBox ID="TextBox57" runat="server" Columns="1">57</asp:TextBox></td> </tr> <tr> <td><asp:TextBox ID="TextBox2" runat="server">Worker</asp:TextBox></td> <td class="egen"><asp:TextBox ID="TextBox58" runat="server" Columns="1">58</asp:TextBox></td> <td class="ue"><asp:TextBox ID="TextBox59" runat="server" Columns="1">59</asp:TextBox></td> </tr> <tr> <td align="right">Sum:</td> <td align="center"><span id="sum"></span></td> <td align="center"><span id="sum2"></span></td </tr></table>\[/code\]This is my javascript that I use to add up the values in the column egen. \[code\]$(document).ready(function () { //iterate through each td based on class / input and add keyup //handler to trigger sum event $(".egen :input").each(function () { $(this).keyup(function () { calculateSum(); }); });});function calculateSum() { var sum = 0; // iterate through each td based on class and add the values from the input $(".egen :input").each(function () { var value = http://stackoverflow.com/questions/15758871/$(this).val(); // add only if the value is number if (!isNaN(value) && value.length != 0) { sum += parseFloat(value); } }); $('#sum').text(sum);};\[/code\]
 
Back
Top