user2571510
user2571510

Reputation: 11377

How to block checkboxes for checking when certain condition is met in jQuery?

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

Answers (4)

Kartikeya Khosla
Kartikeya Khosla

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);
    }
});

DEMO Link

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);
        }
    });

DEMO Link

Upvotes: 3

dashtinejad
dashtinejad

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.");
    }
});

JSFiddle Demo.

Upvotes: 1

Sam1604
Sam1604

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);
    }
});

DEMO

Upvotes: 1

Alex
Alex

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

Related Questions