nitsuj
nitsuj

Reputation: 780

How do I add and subtract a number in a jQuery .click function?

I will use jQuery to perform the following:

Upon click of elements with the class "checkbox":

My example code does not show all of this function, but I am able to accomplish this except for updating the number that have been clicked / "unclicked".

`

$("span.checkbox").click(function() {

    if(!oldVal) {
        var oldVal = "0";
    }

    var newVal = parseFloat(oldVal) + 1;

    var oldVal = newVal;

    $("#wishlistapps").html('<li>You have ' + newVal + ' apps in your request list</li>');


});

`

Upvotes: 0

Views: 1400

Answers (1)

bfavaretto
bfavaretto

Reputation: 71918

You need to declare your counter variable outside the click handler. The way you are currently doing, oldVal will always be zero when the handler is invoked.

var totalChecked = 0;
$("span.checkbox, span.checkmark").click(function() {
     var el = $(this);
     if(el.hasClass('checkbox')) {
         el.removeClass('checkbox');
         el.addClass('checkmark');
         totalChecked++;
     } else {
         el.removeClass('checkmark');
         el.addClass('checkbox');
         totalChecked--;
     }
     $("#wishlistapps").html('<li>You have ' + totalChecked + ' apps in your request list</li>');
});

Demo: http://jsbin.com/ufopok/2.

You can also use $('.checkmark').length as I said in the comment above, but it can get slow with many checkboxes.

Upvotes: 2

Related Questions