Reputation: 197
I just wanted to make a simple function to try change function but it didn't go as I expected:/
What I am trying to do: 1- as a cost checkboxe is checked, assign the cost like(cost1.checked ? cost1 = 10 : 0) 2- as a checkbox is checked give a result with sum of the checkbox costs.
Problem I get : [object HTMLInputElement][object HTMLInputElement][object HTMLInputElement]
this is the fiddle: http://jsfiddle.net/p3zbm/
this is my code:
$('#cost1').click(function(){
if(this.checked){
var cost1 = 10;
}else{
cost1 = 0;
}
});
$('#cost2').click(function(){
if(this.checked){
var cost2 = 20;
}else{
cost2 = 0;
}
});
$('#cost3').click(function(){
if(this.checked){
var cost3 = 30;
}else{
cost3 = 0;
}
});
$('.costs').change(function(){
var result = cost1 + cost2 + cost3;
$('.total').text(result);
});
I know it's too simple:s
Upvotes: 0
Views: 38
Reputation: 2830
In your code you were actually selecting the checkbox html elements, with this working code, it will accomplish your task::
Example:
var result=0;
$('.costs').change(function(){
$(this).each(function(){
if($(this).prop('checked')){
result=result+parseInt($(this).val());
}else{
result=result-parseInt($(this).val());
}
});
$('.total').text(result);
});
I hope this helps.
Upvotes: 1
Reputation: 60503
declare your variables out of your functions, and try to use a function for recalculation (to be sure that it's called when you want).
var cost1 = 0;
var cost2 = 0;
var cost3 = 0;
function recalculate() {
var result = cost1 + cost2 + cost3;
$('.total').text(result);
}
$('#cost1').click(function(){
cost1 = this.checked ? 10 : 0;
recalculate();
});
$('#cost2').click(function(){
cost2 = this.checked ? 20 : 0;
recalculate();
});
$('#cost3').click(function(){
cost3 = this.checked ? 30 : 0;
recalculate();
});
see jsFiddle
Upvotes: 2