November 13th 2008

Totals and Averages of Column Data on Client Side Using JavaScript and jQuery Demo

Recently, I was asked to provide some totals and an average in the footer of a single table. I’ve done this in the past on the server side and it always turns into a pain for some reason. Its one of those things for me that I don’t have to do to often and have to re-figure out each time :)

Since my focus lately has been learning jQuery, I thought I would try and see if I could achieve the desired end result on the client side using JavaScript. Turns out I made it work so I thought I would write a quick demo on how I did it. Let me know in the comments what I could change to make it better. I’m learning here and don’t mind criticism, especially if you show me a better way.

Live Demo | Download (HTML, CSS, JavaScript)

Screenshot of End Product:

Total and Averages End Product Image

I tried to comment the code so you could quickly figure out what is going on if your learning along with me.


Now that I look back at things, the title of the post might of been a little misleading since I am not showing a total of the values in any of the columns. However, since I got to an average I am sure you can figure out how to leave out the division by count if all you want is a total :)

jQuery Commands/Functions Used:

  • length -The number of elements in the jQuery object.
  • append(content) – Append content to the inside of every matched element.
  • :nth-child(index/even/odd/equation) – Matches all elements that are the nth-child of their parent or that are the parent’s even or odd children.
  • :first – Matches the first selected element.
  • find( expr ) – Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.
  • css( name, value ) – Set a single style property to a value on all matched elements. If a number is provided, it is automatically converted into a pixel value.

Plain Old JavaScript:

Well, I hope I showed you something you hadn’t thought about doing before and maybe pointed you to some useful stuff with the links. Be sure to checkout the Live Demo and let me know in the comments what can be improved or what you would do different.