开发者

running total using jQuery not adding numbers together

I'm trying to create a runn开发者_开发知识库ing total, unsuccessfully, what way would you do this:

var total = 0;
value = $('.price').text();
total += value;
$('#subtotal span').html(total);

All it does it add the next value to the "span" not actually add the figures together!


EDIT: From content of answer posted by OP.

$('.addtocart').click(function(){
                $('#cart').show();
                var omPartNo = $(this).next().text();
                var supPartNo = $(this).next().next().text();
                var cat = $(this).next().next().next().text();
                var desc = $(this).next().next().next().next().text();
                var manuf = $(this).next().next().next().next().next().text();
                var list = $(this).next().next().next().next().next().next().text();
                var disc = $(this).next().next().next().next().next().next().next().text();
                var priceEach = $(this).next().next().next().next().next().next().next().next().text();
                $('#cart table').append('<tr class="tableRow"><td><a class="removeItem" href="#"><img src="/admin/images/delete.png"></img></a><td>' + omPartNo + '</td><td>' + supPartNo + '</td><td>' + cat + '</td><td>' + desc + '</td><td>' + manuf + '</td><td>' + list + '</td><td>' + disc + '</td><td class="price">' + priceEach + '</td></tr>');
                    var total = 0;
                    value = parseInt($('.price').text(), 10);
                    total += value;
                    $('#subtotal span').html(total);
            });

This is my complete code. I think i'm doing this wrong, this isnt going to give me a running total is it??

Any help!?


I think you'll want a .each() here to loop through the elements, using parseFloat() as you go (since they're prices), like this:

var total = 0;
$('.price').each(function() { total += parseFloat($.text([this]));
$('#subtotal span').html(total.toFixed(2));


You can use Number() or + to explicitly cast to a number, which I prefer to parseInt() and parseFloat() for several reasons:

value = +$('.price').text();
total += value;
$('#subtotal span').html(total);

Or, similar to @Nick's sample using each:

var total = 0;
$('.price').each(function() { total += +$.text([this]); });
$('#subtotal span').html(total.toFixed(2));

See also: Hidden Features of JavaScript?


Your code only adds the text from the first element in the jQuery object $('.price'). If you're wanting this selector to add up all the elements that have class 'price'. then you should use the jQuery .each function to loop through the elements adding up the values.

It wouldn't hurt using the parseInt function during the addition as well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜