Reputation: 138
from various stack overflow questions I've managed to get my slider to pretty much where I want it to be, i.e., a slider with a plus and minus with the output
The problem I have is, if I want to display the output more times, dragging the slider works fine, but if I use the plus and minus, it's one figure behind.
HTML
<div class="container">
<div id="minus1" class="minus"><span>-</span></div>
<div id="plus1" class="plus">+</div>
<p>
<input type="text" id="amount_money" style="border:0; color:#ff0000; font-weight:bold;" disabled>
</p>
<div id="slider_1"></div>
<div class="test">0</div>
<div class="test">0</div>
</div>
JS
function changeValue() {
var something = weightSliderValueNew;
$(".test").html("£" + addCommas(something));
}
$("#slider_1").slider({
range: "min",
min: 0,
max: 300000,
step: 50000,
animate: true,
create: function(event, ui) {
$("#amount_money").val("£0");
},
change: function(event, ui) {
$("#amount_money").val("£" + addCommas(ui.value));
$('#slider_1').addClass('red');
},
slide: function(event, ui) {
weightSliderValueNew = ui.value;
changeValue(weightSliderValueNew);
}
});
$("#plus1").click(function(event, ui) {
var value = $("#slider_1").slider("value");
var step = $("#slider_1").slider("option", "step");
$("#slider_1").slider("value", value + step);
weightSliderValueNew = value;
changeValue(weightSliderValueNew);
});
$("#minus1").click(function() {
var value = $("#slider_1").slider("value")
var step = $("#slider_1").slider("option", "step");
$("#slider_1").slider("value", value - step);
weightSliderValueNew = value;
changeValue(weightSliderValueNew);
});
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;
}
Created a fiddle - http://jsfiddle.net/awig/o9hkdupu/2/
Upvotes: 1
Views: 1153
Reputation: 337560
The issue is because your weightSliderValue
is amended differently depending on the event that fired. A much simpler pattern to follow is to read the value from the slider directly and remove the need for the global variable.
You can also tidy the logic a little, so that changeValue()
does all the updates under all events. Try this:
function changeValue() {
var value = '£' + addCommas($('#slider_1').addClass('red').slider("option", "value"));
$(".test").html(value);
$("#amount_money").val(value);
}
$("#slider_1").slider({
range: "min",
min: 0,
max: 300000,
step: 50000,
animate: true,
create: changeValue,
change: changeValue,
slide: changeValue
});
Upvotes: 1