Skip to content Skip to sidebar Skip to footer

How Do I Get, Parse And Sum All The Tds' Of A Table With Jquery?

I have a table with an id '#stock-hotdogs' where the last column is always of the class '.subtotal'. The subtotal is always on this format: $99.00 . So what I need to know is how

Solution 1:

You could do:

var cents_total = 0;

$('#stock-hotdogs .subtotal').each(function() {
    var value = $.trim($(this).text());
    var parts = value.substr(1).split('.');
    cents_total += +parts[0] * 100 + (+parts[1] || 0);
});

I don't use parseFloat here because one should not use float values for financial computations (rounding error). Should be trivial to convert the cent values to dollars :)

Solution 2:

var inputs = $('td.subtotal', '#stock-hotdogs').find('input');

var total = 0;

$(inputs).each(function() {
    total += parseFloat( $(this).val().replace(/[^\d\.]+/g, ''));
});

Here is a live working example OR

A second version that isn't using input elements...

$('#totalbtn').click(function() {
    var total = 0;
    $('td.subtotal', '#stock-hotdogs').each(function() {
        total += parseFloat( $(this).text().replace(/[^\d\.]+/g, ''));
    });

});

HERE is an example for this...

Solution 3:

var subTotals = $('#stock-hotdogs td.subtotal');
var sum = 0;

subTotals.each(function() {
    sum += parseFloat($(this).text().substr(1));
});

alert(sum);

Working Example: http://jsfiddle.net/FishBasketGordo/f5V9P/

Solution 4:

Use:

var total=0;
$('#stock-hotdogs .subtotal').text(function(i,v){
    total+=parseFloat(v.substr(1));
});

alert('total: $'+total.toFixed(2));

Solution 5:

Take a look at the JQuery Calculation plugin: it lets you specify which fields to sum using jQuery selectors. Using it you would do something like this:

$("#stock-hotdogs").find("td.subtotal").sum();

Post a Comment for "How Do I Get, Parse And Sum All The Tds' Of A Table With Jquery?"