Function call after checking a certain number of flags

I try to wash the div as soon as a certain number of checkboxes are checked, but I cannot get it to work. I tried val and length , but I suppose that I do not believe the value of the correct path for the flags?

$('input:checkbox').change(
    function(){
        if ($(this).is(':checked').val > 2) {
            alert('checked');
        }
    });

Any input would be greatly appreciated. Thank!

+4
source share
2 answers

You can use the selector and check the number of elements found ( lengthindicates this).

$('input:checkbox').change(function() {
    var numberChecked = $('input:checkbox:checked').length;
    if (numberChecked > 2) {
        // Fade your div out here
    }
});
+8
source

You can try the following:

 $('input:checkbox').change(
function () {
    var checkboxesChecked = 0;
    $('input:checkbox').each(function() {
        if ($(this).is(':checked')) {
            checkboxesChecked++;
        }
    });

    if (checkboxesChecked > 2) {
        alert('More than 2 checkboxes are checked.');
    }
});
+2
source

All Articles