문제

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.

도움이 되었습니까?

해결책

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(/\$/, '');
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top