Simon Martin
Simon Martin

Reputation: 4231

sumtr on cells formatted as currency

I am using sumtr to sum up a column but I'd like to be able to calculate the sum from a column that's formatted for currency.

$('#Cart').sumtr({
    readValue: function (e) { return Number(parseFloat(e.data('val'))
                             .replace(/[^0-9\.]+/g, "")); },
    formatValue: function (val) { return formatCurrency(val); }
});

If I remove the readValue above then the code works fine, it totals up a column that does not have a currency symbol; I'm using the formatCurrency() method to display the total formatted with a currency symbol.
However if the column (with class "sum") is already formatted with currency then sumtr doesn't work with the values. So I've tried to get the readValue function to strip out anything but Numbers, but nothing is returned.

This is a part of the table sumtr is working on

<tr>
    <td>Adrobupicator</td>
    <td class="currency">&#163;700.01</td>
    <td>1</td>
    <td class="sum currency">700.01</td>
</tr>
<tr>
    <td>A1 Product 2</td>
    <td class="currency">&#163;36.28</td>
    <td>1</td>
    <td class="sum currency">36.28</td>
</tr>
<tfoot>
    <tr class="summary">
        <td colspan="3">Cart Total</td>
        <td class="currency"></td>
    </tr>
</tfoot>

Upvotes: 1

Views: 864

Answers (1)

Simon C
Simon C

Reputation: 9508

if you are using e.data('val'), it implies that you have set soem data vals on the td which I don't think you have done?

So you could either parse the td html like so:

$('#myTable').sumtr({
    readValue : function(e) { return parseFloat(e.html().replace(/[^0-9\.]+/g, "")); },
    formatValue : function(val) { return '$' + val; },
});

OR you can use e.data('val') if you have set the data. Then you wouldn't even need the regex. Either use data-attributes:

<tr>
    <td class="currency" data-val="700.01">&#163;700.01</td>
</tr>

or set the data explicitly using jQuery:

$("#yourtd").data("val", 700.01);

Upvotes: 1

Related Questions