0

I have 3 span tags that hold the price for each item and shipping. I need to add the three span tags together to come up with the total price using jQuery. Here is my code:

<div id="relative">
    <div id="absolute">
        Widget 1: <span id="widget_1_price">$99.99</span><br />
        Widget 2: <span id="widget_2_price">$14.99</span><br />
        Shipping Fee: <span id="shipping_price">$10.00</span><br />
        <b>Total: <span id="total_price"></span></b>
    </div>
</div>

I have tried several methods but none seem to work for me.

three3
  • 2,756
  • 14
  • 57
  • 85

3 Answers3

2

Loop through the elements and parse the text in them, and add them together:

var sum = 0;
$('#widget_1_price,#widget_2_price,#shipping_price').each(function(){
  sum += parseFloat($(this).text().substr(1));
});
$('#total_price').text('$' + Math.round(sum * 100) / 100);

Demo: http://jsfiddle.net/QTMsE/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    Yes, though the ideal would be to remove the `$` from the `span`, so the JS is a little less dependent on the specifics of the markup... – lonesomeday Feb 10 '13 at 17:25
  • 1
    Better multiply by `100` *before* you add the numbers. You know, floating point precision. – Felix Kling Feb 10 '13 at 17:27
  • @mplungjan: Rounding works fine. I avoid `toFixed` because of the various bugs in the implementation in various browsers. – Guffa Feb 10 '13 at 17:51
  • Which? Worse ones than what sometimes happen when you divide? Hmm http://stackoverflow.com/questions/5490687/broken-tofixed-implementation – mplungjan Feb 10 '13 at 18:02
0
var val1 = parseFloat($("#widget_1_price").text().substring(1));
var val2 = parseFloat($("#widget_2_price").text().substring(1));
var shipping = parseFloat($("#shipping_price").text().substring(1));

var all = val1 + val2 + shipping;
$("#total_price").text("$"+all);

Try this.

Tim Daubenschütz
  • 2,053
  • 6
  • 23
  • 39
0

Try this:

total = parseFloat($('#widget_1_price').text().slice(1))+
        parseFloat($('#widget_2_price').text().slice(1))+
        parseFloat($('#shipping_price').text().slice(1));

$('#total_price').text('$'+total);
Jai
  • 74,255
  • 12
  • 74
  • 103