Question

I'm attempting to add 2 values together with jQuery. I have a table with these values:

<table>
<tr id="fc_cart_foot_subtotal">
<td class="fc_col2">$7.95</td>
</tr>
<tr id="fc_cart_foot_shipping">
<td class="fc_col2">$4.00</td>
</tr>
<tr id="fc_cart_foot_total">
<td class="fc_col2">$7.95</td>
</tr>
</table>

I need to add the value of #fc_cart_foot_subtotal .fc_col2:

<tr id="fc_cart_foot_subtotal">
<td class="fc_col2">$7.95</td>
</tr>

to the value of #fc_cart_foot_shipping .fc_col2:

<tr id="fc_cart_foot_shipping">
<td class="fc_col2">$4.00</td>
</tr>

and have the value of #fc_cart_foot_total .fc_col2 updated

<tr id="fc_cart_foot_total">
<td class="fc_col2">$7.95</td>
</tr>

So in this example, the first subtotal value of $7.95 should add $4.00 to give a total of $11.95. The subtotal and shipping cost will change, so I'll need to be able to "grab" those values as they change and use them in an equation.

Was it helpful?

Solution

To convert the dollar string into a number for addition:

function parseDollar(str) {
   return +str.substr(1);
}

Then to add the numbers together and format it correctly:

$('#fc_cart_foot_total .fc_col2').text('$' + (
    parseDollar($('#fc_cart_foot_subtotal .fc_col2').text()) +
    parseDollar($('#fc_cart_foot_shipping .fc_col2').text())
).toFixed(2));

If it is possible that you can get negative dollar values e.g. "-$1.00", then change parseDollar to:

function parseDollar(str) {
    return +str.replace(/\$/, '');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top