1

How can I add the corresponding values when each button is clicked?

With my current script it almost works but it adds each of the previous values instead of just adding the current value:

jQuery(function() {
    total = 0;
    jQuery("input").click(function() {
        jQuery("input:checked").not('input[value="reset"]').each(function() {
            total += parseFloat(jQuery(this).val());
        });
        jQuery("#Totalcost").html("Save up to " + total + "%");
    });

    jQuery('input[value="reset"]').click(function(){
        jQuery('span#Totalcost').html("Calculate your Savings!");
        total = 0;
    });
});
1
  • please show us the HTML also Commented Mar 5, 2015 at 22:32

2 Answers 2

2

Try to declare global visible variable.

JSFiddle

var total = 0;

jQuery(function() {

    jQuery("input").click(function() {
        jQuery("input:checked").not('input[value="reset"]').each(function() {
            total += parseFloat(jQuery(this).val());
        });
        jQuery("#Totalcost").html("Save up to " + total + "%");
    });

    jQuery('input[value="reset"]').click(function(){
        jQuery('span#Totalcost').html("Calculate your Savings!");
        jQuery("input:checked").prop('checked', false);
        total = 0;
    });
});

Information

total variable is declared outsite jQuery(function (){ because I dont know do You not need this variable outside this function.

Btw. Maybe You are interested jQuery change event?

I think this is better choice in this case.

Sign up to request clarification or add additional context in comments.

1 Comment

Edited. Unchecking all checked inputs, was added.
0

You don't set your total back to zero each time a checkbox is clicked. Reset your total back to zero within your click event handler:

jQuery(function() {
    var total = 0;
    jQuery("input").click(function() {
        total = 0;
        jQuery("input:checked").not('input[value="reset"]').each(function() {
            total += parseFloat(jQuery(this).val());
        });
        jQuery("#Totalcost").html("Save up to " + total + "%");
    });

    jQuery('input[value="reset"]').click(function(){
        jQuery('span#Totalcost').html("Calculate your Savings!");
        total = 0;
    });
});

JSFiddle

1 Comment

This almost works, except for the Reset button. How can I make it work? When a user presses Reset, it should uncheck all the inputs and set the total to 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.