I have the following input
:
<input id="meepmeep" type="range" min="0" max="128" step="1" value="0" />
And I'm doing a basic setInterval()
call:
setInterval(function() {
var newVal = $('#meepmeep').val() + 1;
$('#meepmeep').val(newVal);
}, 500);
But the incremented val() + 1
seems to be val() + 50
any ideas?!
Fiddle for the lazy: /
I have the following input
:
<input id="meepmeep" type="range" min="0" max="128" step="1" value="0" />
And I'm doing a basic setInterval()
call:
setInterval(function() {
var newVal = $('#meepmeep').val() + 1;
$('#meepmeep').val(newVal);
}, 500);
But the incremented val() + 1
seems to be val() + 50
any ideas?!
Fiddle for the lazy: http://jsfiddle/neuroflux/SNYsa/
Share Improve this question asked Oct 14, 2013 at 11:36 Barrie ReaderBarrie Reader 10.7k11 gold badges77 silver badges141 bronze badges5 Answers
Reset to default 4The value is parsed as a String. Convert the datatype to a number to fix the issue:
setInterval(function() {
var newVal = parseInt($('#meepmeep').val()) + 1;
$('#meepmeep').val(newVal);
}, 500);
Here is a generic function that will slide to a given value on a range for a given jQuery element.
$("button").on("click", function(){
slideToValue(75, $("#slider"));
});
function slideToValue(num, $input) {
const interval = function() {
const cur = $input.val();
if (cur < num) {
console.log(`Value is ${cur}. Incrementing!`);
$input.val(parseInt(cur) + 1);
} else if (cur > num) {
console.log(`Value is ${cur}. Decrementing!`);
$input.val(parseInt(cur) - 1);
} else {
console.log(`Arrived at ${num}!`);
clearInterval(slowly);
}
}
const slowly = setInterval(interval, 10);
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Set to 75</button>
<input type="range" id="slider">
That's because .val()
returns a string, you should convert the string to a number before addition:
setInterval(function() {
$('#meepmeep').val(function(i, str) { return ++str; });
}, 500);
http://jsfiddle/SNYsa/1/
setInterval(function() {
var newVal = parseInt($('#meepmeep').val()) + 1.0;
$('#meepmeep').val(newVal);
}, 500);
works fine ;)
var newVal = $('#meepmeep').val() + 1;
Result
Run
1st time value = 1
2nd time = 11
3rd time = 111
4th time = 1111
Because you are adding to string
not converting it to integer value
Correct Code Jsfiddle
setInterval(function() {
var newVal = $('#meepmeep').val(function(i, val) {
return +val + 1;
});
}, 500);
or Jsfiddle
setInterval(function() {
var newVal = parseInt($('#meepmeep').val()) + 1;
$('#meepmeep').val(newVal);
}, 500);
Read parseInt()