Add it Up

This is another in my ongoing series of posts called “Hey dummy, you figured this out once so write it down in case you ever need it again.”

Have you ever needed to sum up a column in an HTML table using JavaScript? Now how about only summing the column if another column in that row is checked? Here’s an example of what I mean. Suppose you had this table:

Pay View Detail Download Pdf Invoice Date Amount Balance
16072 Download 12/15/10 $219.96 $19.96
16078 Download 01/15/11 $219.96 $219.96
16090 Download 02/15/11 $219.96 $219.96

and you wanted to add up the Balance field of the checked rows.

Once again, jQuery makes this trivial. Here’s the entirety of the code:


var sum = 0;
$('[id^="chkPay"]:checked').each(function() {
sum += parseFloat(($(this).parent().nextAll().eq(4).text().substring(1)) );

});
alert(sum);

What is this doing exactly? Let’s break it down.

1. For each selected row:
$('[id^="chkPay"]:checked').each()
If you inspect the HTML of the code above using FireBug or Developer Tools or even View Source, you’d see how the checkboxes id’s start with a specific string, in this case ‘chkPay’. This selector in jQuery says “For each of the checkboxes whose id’s start that way, do the following function.

2. $(this).parent()
Within the ‘each()’ function, $(this) refers to the checkbox itself. Adding $(this).parent() points to the

that contains the checkbox.

3. .nextAll().eq(4)
This essentially says ‘Go 5 siblings over,’ [5 because it’s zero-indexed], which means 5

columns from the checkboxes parent. That’s the “Balance” column.

4. .text().substring(1)
That pulls the Balance out of the column, and strips off the leading dollar sign.

5. sum += parseFloat()
Converts the text to a floating point number and adds it to our running balance.

So there you go, essentially one line of jQuery code to perform what we want.

What would be interesting, and I wouldn’t be surprised if someone hasn’t already done this as it seems that everything cool has already been done, is a SQL-type syntax in jQuery for querying tables. Something like this…

$("#tblInvoices").select("Sum(Column(5))","Column(0) : checked")

Perhaps I’ll work on that jQuery plugin in my free time. Ha!

Ok, future Eric and anybody else who might stumble upon this, I hope this helps.

P.S. A big shout out to jsFiddle.net for a very cool site to help me test and debug this jQuery!


Posted

in

by

Tags:

Comments

One response to “Add it Up”

  1. Shalonda Avatar

    Heya i am for the primary time here. I came across this board and I in finding It really useful & it helped me out a lot. I’m hoping to provide one thing back and help others such as you helped me.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.