16 December, 2010

Check uncheck jquery plugin

I needed check all - uncheck all checkboxes feature to be added to lots of pages in one of my site, so thought of creating a jquery plugin for it, so that i would not have to write same piece of code here and there. So here's the plugin, if Check All checkbox is checked all the sub checkboxes are checked and vice-versa, and if Check All is checked and then any of the sub checkboxes is unchecked, then Check All will also be unchecked.

(function($) {
$.fn.extend({
checkun: function(options) {
var defaults = {
chkAllName : "",
chkBoxName : ""
}
var options = $.extend(defaults, options);
var chkAll = options.chkAllName;
var chkBoxs = options.chkBoxName;
var chkBoxesLength = $("input[name='"+chkBoxs+"']").length;

$("input[name='"+chkAll+"']").click(function() {
//get checked state of chkAll checkbox
var chkState = $(this).attr("checked");
if(chkState) {
$("input[name='"+chkBoxs+"']").attr("checked", true);
}
else {
$("input[name='"+chkBoxs+"']").attr("checked", false);
}
});
$("input[name='"+chkBoxs+"']").click(function() {
var subChkState = $(this).attr("checked");
if(subChkState) {
//get the total checkboxes and total checked checkboxes
var chkedLen = $("input[name='"+chkBoxs+"']:checked").length;
if(chkedLen == chkBoxesLength) {
$("input[name='"+chkAll+"']").attr("checked", true);
}
}
else {
//uncheck the chkAll checkbox
$("input[name='"+chkAll+"']").attr("checked", false);
}
});
}
});
})(jQuery);

And to test it, we use the following

//load jquery.js

//  Check All
//
//

Thats it. Hope this helps someone.

1 comment:

Anonymous said...

Thanks,
this is nice one works for me easly. Very nice post thanks again keep it up.