问题
I'm building a form using the "snap to increments" JQuery UI Slider: https://jqueryui.com/slider/#steps
I'm using the following code so that the slider has a custom min of 2501 but still increments on the even 500 (without adding that extra 1) until it reaches a max of 50000. So the step increments look like this: 2501 > 3000 > 3500 > 4000 etc. until it reaches 50000.
<script>
$(function() {
$("#slider").slider({
value: 10000,
min: 2501,
max: 50001,
step: 500,
range: "min",
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;
}
});
</script>
I need to have that value: 10000 so that the slider loads on that specific step, but the problem is that it prints on the page as 10001 instead of 10000.
Any tips on how to tackle this issue?
Thanks!
回答1:
A possible solution is to correct your addCommas function:
$(function () {
$("#slider").slider({
value: 10000,
min: 2501,
max: 50500,
step: 500,
range: "min",
slide: function(event, ui) {
var x = Number(ui.value);
if (x > 2501) {
x = x - (x % 500);
}
$("#amount").val('$' + addCommas(x));
}
});
$("#amount").val('$' + addCommas($("#slider").slider("value")));
function addCommas(nStr) {
var x = Number(nStr);
if (x > 2501) {
x = x - (x % 500);
}
nStr = x.toString();
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;
}
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>
<label for="amount">Amount ($50 increments):</label>
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div id="slider"></div>
来源:https://stackoverflow.com/questions/36813696/jquery-ui-slider-default-value-issues-when-using-custom-step-increments