Calculating The Sum of Inputs
Greetings all, here’s a quick plugin to sum up the values of inputs or even html elements. I wrote this plugin recently for a fellow developer who had a series of input boxes that needed to be totaled. Let’s first take a look at the html:
1 2 3 4 5 6 | Price 1: <input type="text" name="price01" class="price" /><br/> Price 2: <input type="text" name="price02" class="price" /><br/> Price 3: <input type="text" name="price03" class="price" /><br/> Price 4: <input type="text" name="price04" class="price" /><br/> Price 5: <input type="text" name="price05" class="price" /><br/> Total: <span class="total"></span> |
The HTML above allows for entering a price for each of five items. (price01 through price05). While it is possible to manually select each element and sum their totals, in the actual use case there are a number of additional inputs.
1 2 3 4 5 6 7 8 9 10 11 12 | $.fn.sumValues = function() { var sum = 0; this.each(function() { if ( $(this).is(':input') ) { var val = $(this).val(); } else { var val = $(this).text(); } sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 ); }); return sum; }; |
Now the actual plugin starts by iterating over each of the inputs that the user selected (in our case the selector is input.price) and keeps a running tally. Line 4 determines of the current element selected is an input element, otherwise it uses the .text() jQuery method to return the contents of the element minus any HTML tags. Line 9 strips out any non-digit characters, – and . and parses the string into a float. ('0' + val) portion ensures that we have at least a value in the field. Finally the second argument to parseFloat() ensures that the float is parsed in base 10 for the conditions where the user entered a leading zero.
Finally, let’s make use of our plugin and wire it up:
1 2 3 4 5 | $(document).ready(function() { $('input.price').bind('keyup', function() { $('span.total').html( $('input.price').sumValues() ); }); }); |
On line 2 we bind the keyup event to all inputs with a class of price, sum up the values of those inputs and assign the result to span.total. There you go!
Until next time,
- Jonathan
Wow, exactly what I needed!
Russell Albin
6 Nov 09 at 10:41 am
Very nice I use same technique a lot. But couldn’t each this be written:
this.each(function(){
sum += parseFloat( (’0′ + $(this)[ $(this).is(':input') ? 'val' : 'text']()).replace(/[^0-9-\.]/g, ”), 10 );
});
to be a bit shorter.
p.s. Proto is a bit better for those kind of stuff than jquery
Radoslav Stankov
6 Nov 09 at 5:04 pm