Hello all,
I have successfully used the code below to display a numbers field as money in a repeater.
The issue I am having is once a user runs a filter on the repeater the numbers field reverts back to plain numbers without the currency string. I would like the numbers field to continue to display as money after they have run a filter.
Any advice would be greatly appreciated.
$w.onReady(() => {
$w("#dataset1").onReady(() => {
$w('#repeater1').forEachItem( ($w, itemData, index) => {
const numberWithCommas = (x) => {
return "$" + x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " USD";
}
$w('#text31').text = numberWithCommas(parseInt($w('#text31').text));
} );
});
});
Do not connect the text element with the dataset
instead get the data from itemData
and use onItemReady instead of forLoop
// use a inbuild currency convertor instead of regex const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2 }) $w.onReady(() => { $w("#dataset1").onReady(() => { $w('#repeater1').onItemReady( ($w, itemData, index) => { let price = itemData.price; // .price is the field key got from the database $w('#text31').text = formatter.format(price); } ); }); });
Instead of REGEX, you may want to consider using toLocaleString() method with currency locale (which is simpler imho):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
and if you have many items to populate, you should use Intl.NumberFormat :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
Swap out forEachItem() for onItemReady(), but don't wait for the dataset to be ready (maybe you'd get away with it, but there's a distinct possibility you'd be setting the handler just after it would get called).
https://www.wix.com/corvid/reference/$w.Repeater.html#onItemReady