Use jQuery to Tally Forms
Recently, I had the task of creating a simple form to be submitted to a specific department member here on campus. I felt this was a great opportunity to utilize jQuery and to see just how simple I could make adding new fields, since I wanted the form to be somewhat dynamic (adding/removing of inputs and such).
After trying a few methods here and there, I was able to utilize a few jQuery functions and a nice plugin (jquery-formatcurrency) to make everything work as desired.
Here is what I came up with:
$(document).ready(function(){ var total = 0; $('.currency').blur(function() { total = 0; $('.add').each(function(i,obj){ total += $(obj).val()*1; }); $('.subtract').each(function(i,obj){ total -= $(obj).val()*1; }); $('#total').val(total); $('.currency').formatCurrency({symbol:''}); }); });
What's neat about this method is that it handles everything on the blur (loss of focus) of any element with the 'currency' class applied. That means it won't do anything to the field while a person is typing in it -- annoying for some people -- it waits until the user moves on to the next field or away from the field altogether.
The really cool part of what happens first is the mathematical operation. Notice the similarity between the following methods:
$('.add').each(function(i,obj){ total += $(obj).val()*1; }); $('.subtract').each(function(i,obj){ total -= $(obj).val()*1; });
The first method looks at all elements with the 'add' class applied. The .each jQuery function cycles through each matched element and feeds two variables to the attached function: an incremented index and the object reference itself. This makes a tally extremely simple as jQuery will automagically cycle through all the elements you want to either add or subtract based on what class you have applied. The same applies to both classes and, of course, can be extended if you want to do more complex mathematics or formatting to your fields.
After these methods run, the total variable now holds the correct sum for all fields properly classed either 'add' or 'subtract.' This can now be applied to the input field with an id of 'total':
$('#total').val(total);
This will set the 'total' input field's value to the sum of the fields.
Lastly, it will format all fields to currency using the formatCurrency function:
$('.currency').formatCurrency({symbol:''});
Notice I specify here that I do not want any currency symbol (e.g. '$') as I specify that outside the field itself to display to the user.
Again, all of this happens every time a field gets updated and loses focus. So yes, it's magic.
