Reputation: 2615
Hello I got a question regarding manipulating the range slider via buttons. I created two buttons which one decrease the value and the other increase the value as can be seen within this FIDDLE.
But I have some issue with it. As you can see if your press multiple times the less button only the second time the value of my current_value
variable is updated. What do I do wrong. This also introduce the problem that whenever you pressed the "less" button and after that you press the "more" button then also the current_value
is not updated.
This is my JS Code:
$('.more, .less').click("on", function (e) {
e.preventDefault();
var current_value = parseInt($('input').val());
if (current_value == 100 || current_value == 0) {
return;
}
var classname = $(this).attr("class");
if (classname === "less") {
$('input').val(current_value-10);
} else {
$('input').val(current_value+10);
}
$('#result').html("$" + current_value);
});
Can anyone tell me why this is?
Upvotes: 0
Views: 2659
Reputation: 4429
Try using a click and a change handler to get your slider working properly:
$('.more,.less').click(function(){
var value = parseInt($('#price').val());
switch($(this).hasClass('more')){
case true:
value = value === 100 ? value : value +5;
break;
case false:
value = value === 0 ? value : value -5;
break;
}
$('#price').val(value).trigger('change');
});
$('#price').change(function(e){
e.preventDefault();
var current_value = parseInt($('input').val());
$('#result').html("$" + current_value);
});
Fiddle showing this working: https://jsfiddle.net/1cmato26/3/
Upvotes: 2
Reputation: 136
it seems to work fine other than the fact that it won't update value once it reaches 0 or 100 because you have a return for both more or less
Upvotes: 1
Reputation: 4597
because of this statemant
if(current_value == 100 || current_value == 0){
return;
}
when you reach 100
or 0
value you will not be able to change the value of input because it will always return 0
just try
$('.more, .less').click("on", function(e) {
e.preventDefault();
var current_value = parseInt($('input').val());
var classname = $(this).attr("class");
if (classname === "less") {
if (current_value == 0)
return;
else {
$('input').val(current_value - 10);
$('#result').html("$" + (current_value - 10));
}
} else {
if (current_value == 100)
return;
else {
$('input').val(current_value + 10);
$('#result').html("$" + (current_value + 10));
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="margin-top: 1em">
<h2>Price</h2>
<button class="less">
less
</button>
<input id="price" type="range" min="0" max="100" step="5" value="50" />
<button class="more">
more
</button>
</div>
<p id="result">$50</p>
Upvotes: 2