How to select rows and sum a column with a button?
How to select rows and sum a column with a button?

Link to test case:
http://live.datatables.net/kilehemo/14/edit
Description of problem:
As seen in the above example, I know a) how to select/deselect rows and sum the total of one of their columns using a callback function, and I know b) how to select/deselect a "set" of rows using buttons.
How can I combine those so that I select a "set" of rows with a button and sum one one of their columns? In the example, when I select a set of rows, the total age remains at zero.
I need some code where I've commented out the 17th and 18th lines of my JavaScript that passes the row or the staffid to my sumRows
function. I am inexperienced with JavaScript/jQuery, so part of the problem is that I don't know how to pass a value into a function, where the function also has to process a (this)
selector.
Any help would be greatly appreciated.
This question has accepted answers - jump to:
Answers
Thanks for the test case! You can use the sum() plugin to get the sum of a Datatables dataset. See this updated example:
http://live.datatables.net/kilehemo/15/edit
Changes made to your example:
sumRows()
after the loop in your buttonFirst it retrieves the selected rows using the
row-selector
of{selected: true}
. See this example. It usesrows().data()
to get the data of the selected rows. Thepluck()
API returns just the column needed.pluck(3)
is theAge
column. Thesum()
plugin sums the resulting data set.Kevin
`
Thank you very much @kthorngren
I found with your example that the effect of individual row clicks on the total was delayed by 1 click, so it wasn't working as expected. I have managed to get it working correctly by splitting it into 2 functions, as shown in this example. Obviously it's not as compact or as simple. Perhaps there's a simpler fix for your example?
Regarding
pluck()
, is there a property for that, or an alternative function, that will do the same thing, but target columns by a class on the th or td? My real project requires summing of multiple columns (individually), and their order may not always be the same.I didn't test for additional selections
With
pluck()
you can use array notation or if you are using objects, iecolumns.data
, you use the object key.You can use
cells()
with arow-selector
of the indexes of the selected rows and acell-selector
containing a classname assigned to theth
. Update example:http://live.datatables.net/kilehemo/19/edit
Changed:
To:
And added the classname
col-age
to theth
.Kevin
Great. Thanks Kevin
I understand now what you mean. I believe the row click event is happening before the selection process so you are inverting the
($(this).hasClass('selected')
boolean.Kevin