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

by Bill Beckelman 13. November 2008 07:26

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  (Contains both aspx and html version of the end product)

 

Screenshot of End Product:

Table With Total and Averages 

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

jQuery:

    <script type="text/javascript">
        $(document).ready(function() {
            //Get the total count of the rows.
            var count = $("#tableOne tbody td:nth-child(1)").length;

            //Append the count to the text all ready in the first cell
            $("#tableOne tfoot td:first").append(count);

            //Starting with the fourth column compute the average of the scores
            for (i = 4; i <= 8; i++) {
                var total = 0;                

                //Get a set of all the scores from the current column
                var wrappedSet = $("#tableOne tbody").find("td:nth-child(" + i + ")");

                //Add the scores
                $(wrappedSet).each(function() {
                    $(this).css("text-align", "right");

                    //By using javascript Number() we can add things up and not concatenate strings
                    //Depending upon data might want to do some checking to make sure the text is a 
                    //number first
                    total += Number($(this).text());
                });

                //Compute the average and place it in the appropriate footer cell
                //Have to use javascript toFixed() to get a reasonable string
                $("#tableOne tfoot td:nth-child(" + i + ")")
                    .text((total / count).toFixed(2) + "%")
                    .css("text-align", "right");
            }
        });                             
    </script>
 

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.

    kick it on DotNetKicks.com

Tags:

ASP.NET | jQuery

Comments


About Me

I live and work in Salt Lake City, Utah. My background is in aviation. I have a degree in Aeronautical Science from Embry-Riddle Aeronautical University in Prescott, AZ. I have worked as a commercial airline pilot and most recently as a technical advisor for a charter airline.