I'm coding a jQuery plugin that basically checks if a set of checkboxes groups have at least x
options checked. A checkbox group is named as name=group[]
. You'd call the plugin like:
$(':checkbox').checkpass({min: 1}) // Make sure at least one checkbox per group is checked
I've been working on this piece of code for a couple days trying to make it as short and fast as possible because I'm going to implement this on a very large form
. Is it possible to make it shorter/faster, or have I reached the limit?
You can check a live example here.
(function($) {
$.fn.checkpass = function(options) {
var opt = $.extend({
min: function() {
return (min === 'undefined') ? 1 : min;
},
errorContainer: '<ul class="checkpass-errors">',
errorWrap: '<li class="error">'
}, options);
var $ckboxes = this,
names = [],
num = 0,
$errors = $(opt.errorContainer);
$ckboxes.each(function() {
var name = this.name;
if (!~$.inArray(name, names)) {
names.push(name);
}
});
for (var i = 0, l = names.length; i < l; i++) {
$checked = $ckboxes.filter('[name="' + names[i] + '"]:checked');
if ($checked[opt.min - 1]) {
num++;
} else {
if (opt.min > 0) {
var $err = $(opt.errorWrap),
_remaining = opt.min - $checked.length,
_name = names[i].match(/\w+/).toString()
.replace(/^\w/, function($0) {
return $0.toUpperCase();
});
$err.html('<strong>' + _name +
':</strong> Check ' +
_remaining + ' more.').appendTo($errors);
}
}
}
return {
isValid: !! (num === names.length),
errors: $errors
};
};
})(jQuery);
shorted !== faster
\$\endgroup\$