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 --> <tr> <td class="booktitle"></td> <td> </td> <td class="pages"></td> <td> </td> <td class="rating"></td> </tr> <!-- final row --> <tr id="summation"> <td id="booktotal"></td> <td></td> <td id="pagesum"></td> <td></td> <td id="ratingAvg"></td> </tr> <script> calculateFigures(); function calculateFigures() { // Calculate total number of pages var pageSum = 0; var books = 0; jQuery('.pages').each(function() { books++; 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); }; </script>