开发者

how do I get, parse and sum all the tds' of a table with jQuery?

开发者 https://www.devze.com 2023-03-26 22:41 出处:网络
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 to get the numbers

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 to get the numbers of all those td's, sum them and store them in a variable. What开发者_JAVA技巧 should be the way to go?


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 :)


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...


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/


Use:

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

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


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消