I’m coding this plugin that validates if a series of checkbox groups have at least x options checked.
Each checkbox group is named with the name attribute like
<input type="checkbox" name="group[]"> // Where `[]` identifies it as a group
And the plugin is called like so:
/* Grab all checkboxes and make sure
at least 2 are checked in every group */
$(':checkbox').checkpass(2);
If you try the plugin at http://jsfiddle.net/elclanrs/GFCKA/ you’ll see that every time you try to validate, an alert will come up with the number of options left per group you need to check. When all conditions are met the message will not trigger anymore. You’ll get the “Passed!” alert.
The plugin works fine if the value passed is greater than one but the problem comes when I pass a value of zero:
$(':checkbox').checkpass(0)
If the minimum is set to zero it still grabs the default value of min = 1 so it acts as if the value passed were 1. Why is this happening? Here’s the actual plugin:
(function($) {
$.fn.checkpass = function(min) {
var $ckboxes = this,
names = [],
num = 0,
err = '';
$ckboxes.each(function() {
var name = this.name;
if (!~$.inArray(name, names)) {
names.push(name);
}
});
min = min || 1;
for (var i = 0, l = names.length; i < l; i++) {
$checked = $ckboxes.filter('[name="' + names[i] + '"]:checked');
if ($checked[min - 1]) {
num++;
} else {
var _remaining = min - $checked.length,
_name = names[i].match(/\w+/).toString()
.replace(/^\w/, function($0) {
return $0.toUpperCase();
});
err += _name + ': Check ' + _remaining + ' more\r\n';
}
}
return {
isValid: num === names.length,
errors: err
};
};
})(jQuery);
// Test
$('button').click(function() {
var checkpass = $(':checkbox').checkpass(3);
if (checkpass.isValid) {
alert('Passed!');
} else {
alert(checkpass.errors);
};
});
It’s because of this logic:
In JavaScript 0 evaluates to false. So the above statement is always setting min to 1 when it is passed in as 0.
You could change it to: