Snippets

Test that at least one checkbox is checked in every group

http://jsfiddle.net/elclanrs/GFCKA/6/
if (!$(‘:checkbox’).atLeastOne()) {
alert(‘error’);
} else {
alert(‘good’);
};

/* 
Group checkboxes with the
name attribute like
`name="group[]"`
*/
(function($) {
    $.fn.atLeastOne = function() {
        var $ckboxes = this,
            names = [],
            num = 0;
        $ckboxes.each(function() {
            var name = this.name;
            if (!~$.inArray(name, names)) {
                names.push(name);
            }
        });
        for (var i = 0, l = names.length; i < l; i++) {
            if ($ckboxes.filter('[name="' + names[i] + '"]:checked').length) {
                num++
            }
        }
        if (num === names.length) {
            return true;
        } else {
            return false;
        }
    };
})(jQuery);

Share this snippet