Book Image

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Book Image

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Overview of this book

Table of Contents (18 chapters)
Learning jQuery
Credits
About the Authors
About the Reviewers
Preface

Numeric Calculations


Now we’ll move on to some manipulation of the actual numbers the user will enter in the shopping cart form. We have a Recalculate button on the form, which would cause the form to be submitted to the server, where new totals can be calculated and the form can be presented again to the user. This requires a round trip that is not necessary, though; all of this work can be done on the browser side using jQuery.

The simplest calculation on this form is for the cell in the Shipping row that displays the total quantity of items ordered. When the user modifies a quantity in one of the rows, we want to add up all of the entered values to produce a new total and display this total in the cell:

$('.quantity input').change(function() {
  var totalQuantity = 0;
  $('.quantity input').each(function() {
    var quantity = parseInt(this.value);
    totalQuantity += quantity;
  });
  $('.shipping .quantity').text(String(totalQuantity));
});

We have several choices for which event to watch...