Reputation: 11377
I have a HTML form with a number of checkboxes that all have the same class = "shared"
.
I figured out how I can count how many of these checkboxes are checked at a time using the following lines but would like to prevent additional checkboxes from being checked when the count has reached 3 so that never more than 3 checkboxes can be checked at a time.
How can I achieve this ?
My jQuery (working part):
$(document).on('click', '.shared', function() {
var countShared = $('.shared:checked').length;
if(countShared > 3) {
alert("You have reached the maximum number of selectable checkboxes.");
}
});
Upvotes: 1
Views: 1158
Reputation: 18873
Instead of click
use change
event (always try to use change event while dealing with checkboxes) and try below code :-
$(document).on('change', '.shared', function() {
var countShared = $('.shared:checked').length;
if(countShared > 3 && $(this).is(':checked')) {
alert("You have reached the maximum number of selectable checkboxes.");
$(this).prop('checked',false);
}
});
OR
$(document).on('change', '.shared', function() {
var countShared = $('.shared:checked').length;
if(countShared > 3) { //<-------------here is the difference
alert("You have reached the maximum number of selectable checkboxes.");
$(this).prop('checked',false);
}
});
Upvotes: 3
Reputation: 6253
Use preventDefault
method:
$(document).on('click', '.shared', function(e) {
var countShared = $('.shared:checked').length;
if(countShared > 3) {
e.preventDefault();
alert("You have reached the maximum number of selectable checkboxes.");
}
});
Upvotes: 1
Reputation: 1489
Add $(this).prop('checked', false);
with your query
$(document).on('click', '.shared', function() {
var countShared = $('.shared:checked').length;
if(countShared > 3) {
alert("You have reached the maximum number of selectable checkboxes.");
$(this).prop('checked', false);
}
});
Upvotes: 1
Reputation: 10216
Just disable them:
$(document).on('click', '.shared', function() {
var countShared = $('.shared:checked').length;
if(countShared > 3) {
alert("You have reached the maximum number of selectable checkboxes.");
$('.shared').not(':checked').prop('disabled', true);
}
});
But you need to make sure when you uncheck a box that you re-enable the other checkboxes.
Upvotes: 1