Reputation: 1957
I'm trying to create a cost calculator. Basically I have values within checkbox inputs and as they are checked, they are added together using jQuery.
$('.option').click(function() {
var total = 0;
$('.option:checked').each(function(){
total += parseInt($(this).val());
});
$('.estimate').html('$' + total);
});
<input class="option" type="checkbox" value="1000" />
<input class="option" type="checkbox" value="200" />
<input class="option" type="checkbox" value="750" />
So in the above example, the total would be 1950. That part of the function works fine, but I want to add two range sliders in to the equation.
<input class="range" type="range" min="0" max="3">
<input class="range" type="range" min="0" max="3">
Each of the 4 positions of the slider would increase the value added to the overall total. How could I add the range slider positions in to the above function?
Here is the jsFiddle: http://jsfiddle.net/2MLKc/
Upvotes: 1
Views: 258
Reputation: 991
Just use the input's change event:
http://jsfiddle.net/EfrainReyes/2MLKc/4/
$(document).ready(function() {
var total;
var addToTotal = function(){
total += parseInt(this.value, 10);
};
var compute = function() {
total = 0;
$('.option:checked,.range').each(addToTotal);
$('.estimate').text('$' + total);
};
$('.option, .range').change(compute);
});
Upvotes: 2
Reputation: 820
Well, you could do something quite similar like with the checkbox. With jQuery you can get the value of a slider input with $(selector).val().
But I recommend to abstract the calculation on another function and call it from the $('.option').click(function()... and the $('.range').change(function()...
Upvotes: 1
Reputation: 348
Here is simple change to what you have to make it work.
$('input').change(function() {
var total = 0;
$('.option:checked').each(function(){
total += parseInt($(this).val());
});
$('.range').each(function(){
total += parseInt($(this).val());
});
$('.estimate').html('$' + total);
});
Upvotes: 2