Reputation: 45
I'm building a form which uses the "snap to increments" JQuery UI slider: https://jqueryui.com/slider/#steps
This is the code I currently have:
<script>
$(function() {
$( "#slider" ).slider({
value:100,
min: 2501,
max: 50000,
step: 500,
slide: function( event, ui ) {
$( "#LoanAmount" ).val( '$' + addCommas(ui.value) );
}
});
$( "#LoanAmount" ).val( "$" + $( "#slider" ).slider( "value" ) );
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>
My first problem is that the code displays the comma for the value only after the slider gets used but not when the page loads. The page loads with the min value of $2501 instead of $2,501
My second problem is that, for compliance reasons, I need the min amount to be $2,501 instead of $2,500 but I still want the step increments to display on the even 500. I need it to be like this: $2,501 > $3,000 > $3,500 > $4,000 > $4,500, until it finishes on $50,000.
Any help will be greatly appreciated. Thanks!
Upvotes: 2
Views: 1794
Reputation: 1886
First heres an easy way to add commas to text, not 100% sure if its supported on all browesers though so use with caution
textvalue = Number(nStr).toLocaleString('en',{minimumFractionDigits: 0 });
For your first problem do this
$( "#LoanAmount" ).val( "$" + $( "#slider" ).slider( "value" ) );
should be
$( "#LoanAmount" ).val( "$" + addCommas($( "#slider" ).slider( "value" )) );
As for the second issue an easy hack would be set the starting value to 2501, then in your slide function do this
slide: function( event, ui ) {
var val = ui.value
if(val === 2500){
val = 2501
}
else{
val = val / 10
val = Math.round(val)
val = val * 10
}
$( "#LoanAmount" ).val( '$' + addCommas(val) );
}
I think this will work, basically you check to see if value is 2500 then you set it to 2501, but then you have to make sure that when you step you round back to an even 500 number
EDIT
fixed bug with code
Upvotes: 2
Reputation: 1196
What if you just manipulate the value in the slide event, like this:
$(function() {
$( "#slider" ).slider({
value:100,
min: 2501,
max: 50001,
step: 500,
slide: function (event, ui) {
var x = Number(ui.value);
if (x > 2501) {
x = x - (x % 500);
}
$("#LoanAmount").val('$' + addCommas(x));
}
});
$("#LoanAmount").val( '$' + addCommas($("#slider").slider("value") ) );
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;
}
});
See this jsfiddle for an example: https://jsfiddle.net/bpursley/u1nLma3x/7/
Upvotes: 3