Hey guys,
I’m trying to figure out a way to add thousand separators to numbers. I’ve searched many places and also in here which was the closest, but a post from 5 years ago which didn’t seem to solve the issue.
I’m using Elementor Pro + Hello theme.
Here’s the code I’m currently using in an HTML widget right before the number I wish to format.
<script>
jQuery(function($){
function numberWithCommas(number) {
var parts = number.toString().split(“.”);
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, “,”);
return parts.join(“.”);
}
$(document).ready(function() {
$(“#price_figure p,#wickydesign h2”).each(function() {
var num = $(this).text();
var commaNum = numberWithCommas(num);
$(this).text(commaNum);
});
});
});
</script>
It shows the formatting on the front end while I am logged into WordPress but as long as I’m logged out, the formatting is lost.
Here are photos to help explain:
[Formatted while logged in](https://preview.redd.it/bj1wce4r35sc1.png?width=303&format=png&auto=webp&s=0ba26bb5c1a3edc5c1a44b9c224079f0bff7696e) [Not formatted when logged out](https://preview.redd.it/rgpvbrms35sc1.png?width=307&format=png&auto=webp&s=5a629eb9b40b13163bb0d0e372648a994a8f1081)If you have a solution, when it’s being proposed, if it is a snippet, let me know also where it should be placed, e.g. in the html widget, CSS or PHP functions. I’m still new to the backend of all this as I relied heavily on the page builder to do the heavy lifting.
Thanks in advance!
[ad_2]
Your jQuery function should be in the head or footer, rather than an html widget. It’s likely not running when logged out. Check console for errors. You see a jQuery undefined error?
This function can be written much more cleanly. Consider rewriting it.
Boom.
https://www.kevinleary.net/blog/currency-formatting-javascript-typescript/