Search form

jQuery: Summarize Table Entries

Simple jQuery script for summarizing the results of my Amazon book listing. Since jQuery is already included in Drupal, I figured I'd use it to summarize the ratings and values.

Note that in Drupal (and WordPress), jQuery defaults to noconflict mode so the "$" shortcut isn't available. You can override this by setting jQuery.noConflict(false) or moving it to another namespace but you may find other things starting to break.

<!-- script assumes a table following this format: -->
<!-- content rows -->
<td class="booktitle"></td>
<td> </td>
<td class="pages"></td>
<td> </td>
<td class="rating"></td>

<!-- final row -->
<tr id="summation">
<td id="booktotal"></td>
<td id="pagesum"></td>
<td id="ratingAvg"></td>


function calculateFigures() {
   // Calculate total number of pages
   var pageSum = 0;
   var books = 0;
   jQuery('.pages').each(function() {
        var pageValue = jQuery(this).text();
        if(!isNaN(pageValue) && pageValue.length != 0) {
            pageSum += parseFloat(pageValue);

   // Calculate average pages per book
   var pageAvg = Math.round(pageSum / books);

   // Calculate total ratings value
   var ratingSum = 0;
   jQuery('.rating').each(function() {
        var ratingValue = jQuery(this).text();
        if(!isNaN(ratingValue) && ratingValue.length != 0) {
            ratingSum += parseFloat(ratingValue);

   // Calculate average rating
   var ratingsAvg = (ratingSum / books).toFixed(2);
   // Return results to the summary row
   jQuery('#booktotal').text("Total books: " + books);
   jQuery('#pagesum').text("Total: " + pageSum + " / Avg: " + pageAvg);  
   jQuery('#ratingAvg').text("Avg rating: " + ratingsAvg);     


Looking for affordable web hosting? Try GreenGeeks for only $3.95/mo. (I'm both an affiliate and a client.)

I participate in the Amazon Associates program. Making your Amazon purchases through my affiliate links supports this site at no additional cost to you: