Reputation: 3147
How do I format all table <td>
elements having the class class="contribution"
using .toLocaleString();
or a similar method that can add commas and currency formatting? The table will never have more than 200 rows, in case that is relevant for performance. Here is the current table body format:
<tbody>
<tr>
<td>2009-01-31</td>
<td class="contribution">-100000.00</td>
<td class="distribution">0.00</td>
<td class="nav">0.00</td>
</tr>
<tr>
<td>2013-05-15</td>
<td class="contribution">0.00</td>
<td class="distribution">56000.00</td>
<td class="nav">64000.00</td>
</tr>
</tbody>
The javascript that I am currently using, which doesnt seem to work, is:
$(document).ready( function() {
$("td.contribution").toLocaleString('en-US');
})
In case it helps, the webpage does have jquery 3 loaded.
Upvotes: 3
Views: 9702
Reputation: 1547
Try this (edited to use currency formatting):
$(document).ready( function() {
$("td.contribution").each(function() { $(this).html(parseFloat($(this).text()).toLocaleString('en-US', {style: 'currency', currency: 'USD'})); })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>2009-01-31</td>
<td class="contribution">-100000.00</td>
<td class="distribution">0.00</td>
<td class="nav">0.00</td>
</tr>
<tr>
<td>2013-05-15</td>
<td class="contribution">0.00</td>
<td class="distribution">56000.00</td>
<td class="nav">64000.00</td>
</tr>
</tbody>
</table>
This calls a function on each cell which replaces the HTML content with the locale-formatted version of the number in the cell. Your original code did not read or write the text within the cell.
Upvotes: 5
Reputation: 1568
Can you try this?
$(document).ready(function () {
$("td.contribution").each(function () {
$(this).text($(this).text().toLocaleString('en-US'));
})
});
Upvotes: -1