Reputation: 1097
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++;
})
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
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
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
Reputation: 8482
If you want checked checbox count you can use :checked
selector like this:
$('.checkbox').live('click', function() {
$('.number').html( '(' + $(':checked').size() + ')');
})
And a few suggestions:
.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)change
event instead of click
.: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