网页上不少都会用到checkbox组,也就是一组checkbox,其中一个为checkall,有全选,和全不选的功能。并且当他组员checkbox依次全选时,checkAll也应自动被选中。

逻辑很简单,但以下的扩展封装的很不错。

请参考

checkGroup.js

(function($){
 $.fn.checkgroup = function(options){
  //merge settings
  settings=$.extend({
   groupSelector:null,
   groupName:'group_name',
   enabledOnly:false
   },options || {});
  
  var ctrl_box=this;
  
  
  //allow a group selector override option
  var grp_slctr = (settings.groupSelector==null) ? 'input[name='+settings.groupName+']' : settings.groupSelector;
  
  //grab only enabled checkboxes if required
  if(settings.enabledOnly)
  {
   grp_slctr += ':enabled';
  }
  
  //attach click event to the "check all" checkbox(s)
  ctrl_box.click(function(e){
   chk_val=(e.target.checked);
   $(grp_slctr).attr('checked',chk_val);
   //if there are other "select all" boxes, sync them
   ctrl_box.attr('checked',chk_val);
  });
  //attach click event to checkboxes in the "group"
  $(grp_slctr).click(function(){
   if(!this.checked)
   {
   ctrl_box.attr('checked',false);
   }
   else
   {
    //if # of chkbxes is equal to # of chkbxes that are checked
    if($(grp_slctr).size()==$(grp_slctr+':checked').size()){
     ctrl_box.attr('checked','checked');
    }
   }
  });
  //make this function chainable within jquery
  return this;
 };
})(jQuery);

页面上:

<input type='checkbox' class='checkall'>checkall<br>
<input class='groupclass' name='group' type='checkbox' disabled="true">chk1<br>
<input class='groupclass' name='group' type='checkbox' disabled="true">chk2<br>
<input class='groupclass' name='group' type='checkbox'>chk3<br>
<input class='groupclass' name='group' type='checkbox'>chk4<br>
<input type='checkbox' class='checkall' id="checkall">

调用:

$(document).ready(function(){

  $('.checkall').checkgroup({groupName:'group',enabledOnly:true});

}

在页面初始化时注册checkgroup。

这样就能很简单的实现checkGroup的功能

其中groupSelector参数可以用任意的jquery选择器,比如ID前缀 class 等等的选择器。