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.”
|Pay||View Detail||Download Pdf||Invoice Date||Amount||Balance|
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;
sum += parseFloat(($(this).parent().nextAll().eq(4).text().substring(1)) );
What is this doing exactly? Let’s break it down.
1. For each selected row:
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.
Within the ‘each()’ function, $(this) refers to the checkbox itself. Adding $(this).parent() points to the
This essentially says ‘Go 5 siblings over,’ [5 because it’s zero-indexed], which means 5
That pulls the Balance out of the column, and strips off the leading dollar sign.
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!
One response to “Add it Up”
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.