Reputation: 155
I'm finally getting around to learning jQuery and just when I start to think I'm getting the hang of things, I get stuck again.
I have a script that counts the number of checked check boxes in a section. If the section reaches a limit, prevents user from making more selections and gives them a message, but should allow them to deselect other check boxes.
I have this working EXCEPT, when they deselect a check box, the error message pops up again, as it's still counting the previous number of check boxes. How do I update the count correctly?
http://jsfiddle.net/MadHatrix/VxscW/3/
HTML
<div class="panel">
<button class="btn-option">1</button>
<input type="checkbox" class="hidden-checkbox" />
<button class="btn-option">2</button>
<input type="checkbox" class="hidden-checkbox" />
<button class="btn-option">3</button>
<input type="checkbox" class="hidden-checkbox" />
</div>
<hr>
<div class="panel">
<button class="btn-option">a</button>
<input type="checkbox" class="hidden-checkbox" />
<button class="btn-option">b</button>
<input type="checkbox" class="hidden-checkbox" />
</div>
JQUERY
$('.panel').on('click', 'button', function () {
var checkbox = $(this).next('input:checkbox');
var checkedTotal = $(this).parent('.panel').find('input[type=checkbox]:checked').length;
if (checkedTotal == 2) {
$(this).removeClass('btn-success');
checkbox.prop('checked', false);
alert('limit has been reached');
} else {
$(this).toggleClass('btn-success');
checkbox.prop("checked", !checkbox.prop("checked"));
}
});
Thanks in advance.
Upvotes: 0
Views: 173
Reputation: 9351
You need check if this(clicked) checkbox already checked or not. If already checked then you need decrement the checkedTotal since this checkbox will be uncheck.
try this:
$('.panel').on('click', 'button', function () {
var checkbox = $(this).next('input:checkbox');
var checkedTotal = $(this).parent('.panel').find('input[type=checkbox]:checked').length;
if(checkbox.prop('checked')) {
checkedTotal =checkedTotal -1;
}
if (checkedTotal == 2) {
$(this).removeClass('btn-success');
checkbox.prop('checked', false);
alert('limit has been reached');
} else {
$(this).toggleClass('btn-success');
checkbox.prop("checked", !checkbox.prop("checked"));
}
});
Upvotes: 2