James
James

Reputation: 1706

counting selected checkboxes with jquery

little new to js and having a problem counting selected boxes, can anyone see what im doing wrong?

fiddle: https://jsfiddle.net/ate9a04u/

js

$(document).ready(function () {
    var maxAllowed = 3;
    $(".rmax").html(maxAllowed);
    $(".subscribtion-content input.checkbox").change(function () {
        var cnt = $(".subscribtion-content input.checkbox:checked").length;
        if (cnt > maxAllowed) {
            $(this).prop("checked", "");
            $(".rcount").html(cnt);
        }
    });
});

Also is there anyway to disable the others when max is reached and versa?

Upvotes: 0

Views: 37

Answers (1)

Ibrahim Khan
Ibrahim Khan

Reputation: 20750

Your counting of selected boxes are perfect. You can disable the others when max is reached like following.

$(document).ready(function () {
    var maxAllowed = 3;
    $(".rmax").html(maxAllowed);

    $(".subscribtion-content input.checkbox").change(function () {
        var checkBox = $(".subscribtion-content input.checkbox")
        var cnt = $(".subscribtion-content input.checkbox:checked").length;
        if (cnt == maxAllowed) {
            checkBox.not(':checked').prop('disabled', true);
        } else {
            checkBox.not(':checked').prop('disabled', false);
        }

        $(".rcount").html(cnt);
    });
});

UPDATED FIDDLE

Upvotes: 3

Related Questions