I am using wordpress and I have a few plugins that I have used to try and assist with some pagespeed score increases. That being said I have done some customization on the site and when I do so I lost the addcommas function it seems to the range slider I have on the bar. I cannot get it to show the commas with the numbers any longer. It is just showing the dollar sign. I have tried disabling the plugins, but it doesn’t seem to make a difference.
The site is www.cjhitch.com
Here’s the slider
<div>
<div id="slider" class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
<i class="bulleft"></i>
<i class="bulright"></i>
<div id="slider-min">
$100,000
</div>
<div id="slider-max">
$2,000,000
</div>
<div class="ui-slider-range ui-widget-header ui-corner-all ui-slider-range-min"></div>
<span class="ui-slider-handle ui-state-default ui-corner-all div-cover" tabindex="0">
<input id="amount" type="text" readonly=""></input>
</span>
</div>
</div>
The equal signs aren’t part of the code, I had to use it to get them to show up.
Here is the JS
<script>
$(function() {
$( "#slider" ).slider({
range: 'min',
value: 250000,
min: 100000,
max: 2000000,
step: 1000,
slide: function( event, ui ) {
$("#amount").val("$" + addCommas(ui.value));
$("#result1").val("$" + formatNumber(Math.round(ui.value*.033 - 2799)));
$("#result2").val("$" + formatNumber(Math.round(ui.value*.06 -5299)));
$("#result3").val("$" + formatNumber(Math.round(ui.value*.06 -3799)));
}
});
function formatNumber (num) {
return num.toString().replace(/(d)(?=(d{3})+(?!d))/g, "$1,")
}
console.info(formatNumber(2665)); // 2,665
console.info(formatNumber(102665)); // 102,665
console.info(formatNumber(111102665)); // 111,102,665
$('#amount').val( "$" + formatNumber($("#slider").slider("value"))).detach().appendTo('.ui-slider-handle');
$('.ui-slider-handle').prepend('<i class="fa fa-usd"></i>');
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(d+)(d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
});
</script>
As you can see, I’ve tried two different kinds, number format and add commas. They have both functioned at a time in the past, but now something seems to be “sanitizing” it.
If anyone knows how to fix this, I would greatly appreciate it!
In my opinion this is because ui.value does not contain dots(.) and you do not split it.
Try this.
of course you can use this function on results for example:
There’s Intl.NumberFormat() for the exact task you are trying to perform. So you might better use it, as it does what it should very convenient. The only downside here is Safari that doesn’t support it as the only browser, but you can use this package:
https://github.com/andyearnshaw/Intl.js
to polyfill.
Here’s a copy from mozilla’s documentation I’ve linked above on the usage: