Tomarz
Tomarz

Reputation: 1097

jQuery increase/decrease number when checking boxes

So I have this code:

HTML

<input type=checkbox class="checkbox" />
<input type=checkbox class="checkbox" />
<input type=checkbox class="checkbox" />
<input type=checkbox class="checkbox" />

<div class="number">
    hello
</div>

JS

var increment2 = 1;
$('.checkbox').live('click', function() {
    $('.number').html( '(' + increment2 + ')');
    increment2++;
})

http://jsfiddle.net/P3zMu/5/

It increments the number when checkbox is clicked, as can be seen in the example. The issue is to increase the number when checkbox is checked and decrease when the checkbox is unchecked. Will be very greatful for any help.

Upvotes: 1

Views: 3281

Answers (3)

Minko Gechev
Minko Gechev

Reputation: 25672

Hi that's your solution: https://jsfiddle.net/P3zMu/254/

HTML

<input type=checkbox class="checkbox" />
<input type=checkbox class="checkbox" />
<input type=checkbox class="checkbox" />
<input type=checkbox class="checkbox" />

<div class="number">
    hello
</div>

JS

var increment2=0; 
$('.checkbox').on('click', function() { 
    if (this.checked) {
        increment2++;                 
    } else {
        increment2--;
    }
    $('.number').html( '(' + increment2 + ')');             
})

Best regards!

Upvotes: 0

PHP Ferrari
PHP Ferrari

Reputation: 15616

Also have a look here checked Selector

<script>
var countChecked = function() {
var n = $( "input:checked" ).length;
$( "div" ).text( n + (n === 1 ? " is" : " are") + " checked!" );
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
</script>

Upvotes: 0

Emre Erkan
Emre Erkan

Reputation: 8482

If you want checked checbox count you can use :checked selector like this:

$('.checkbox').live('click', function() {
    $('.number').html( '(' + $(':checked').size() + ')'); 
})

Example

And a few suggestions:

  1. As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). (from documentation)
  2. I suggest using change event instead of click.
  3. You can select checkboxes with :checkbox selector. If you're using .checkbox class to select checkboxes it might be a better way.

Below code is a shorter version of mgechev's answer. *

var increment2=0;
$('.checkbox').live('change', function() {
    $('.number').html( '(' + (increment2 += this.checked ? 1 : -1) + ')');             
})

Upvotes: 5

Related Questions