Reputation: 875
I'm currently using a range slider for price ranges of £0 to £2,000,000. Currently, everything is working correctly apart from the prices not being formatted as currency (i.e the£500,000 value is currently being shown as £500000 - without the commas). Here's the code:
jQuery
/* SALES SLIDER */
$( "#slider-range-price-sales" ).slider({
range: true,
min: 0,
max: 2000000,
step: 50000,
values: [ 0, 2000000],
slide: function( event, ui ) {
$("#minPrice").val("£" + ui.values[0]).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "£1");
$("#maxPrice").val("£" + ui.values[1]);
}
});
$("#minPrice").val("£" + $("#slider-range-price-sales").slider("values", 0));
$("#maxPrice").val("£" + $("#slider-range-price-sales").slider("values", 1));
HTML
<div id="slider-range-price-sales"></div>
<div class="priceContainer">
<div class="left"><input type="text" id="minPrice" name="minPrice" style="border: 0; color: #3D80E9; background:#F2F2F2; font-weight: bold;" /></div>
<div class="right"><input type="text" id="maxPrice" name="maxPrice" style="border: 0; color: #3D80E9; background:#F2F2F2; font-weight: bold;" /></div>
</div>
http://jsfiddle.net/isherwood/RwfFH/
I've tried reformatting the minimum price with JavaScript .replace to no avail.. any help or suggestions would be greatly appreciated.
Thanks, jamie
Upvotes: 3
Views: 8643
Reputation: 301
To keep in line with what you are doing you just need to make a couple changes. I'll point out that you need to have modified the value before you set it in the .val() operation. Also, replace returns a new string it does not modify the original. That being done, you just needed a little tweak in the regex, $1, will use the matched value in the replace.
$("#minPrice").val("£" + ui.values[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
Upvotes: 4
Reputation: 3397
You can use this function which add comma like you want
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;
}
and the jsFiddle : http://jsfiddle.net/RwfFH/1/.
Upvotes: 3