SelectAll

by LyndseyB

HTML

<fieldset id="f1">    
    <input type="checkbox" class="selectAll" id="chkBoxGroup" />
    <label for="chkBoxGroup"> Select All </label>    
</fieldset>

<br />
<fieldset id="f2">
    <input type="checkbox" class="selectAll" id="chkBoxGroup2" />
    <label for="chkBoxGroup2"> Select All </label>       
</fieldset>

CSS

fieldset {
    width:30%;
}

label {
    float:left;   
}

input {
    float:right;   
    clear:left;
}

JavaScript

(function($) {
    $.fn.selectAll = function() {     
        return this.click(function() {      
           var $elementID = $(this).attr("id");    
           var $checkbox = $("input[name='"+$elementID+"']");            
           var $chStatus = this.checked;                
           
           $('body').find( $checkbox ).each(function() {
               $(this).prop('checked', $chStatus);
           });
        });    
    };
}) ( jQuery );


$(function(){  
    //load function
    $('.selectAll').selectAll();
    
   var i; //counter variable
   for(i=1;i<=10;i++) { //loop through 10 iterations
        var chBox = $("<input type='checkbox' name='chkBoxGroup' id='chkBoxID_"+i+"' value='1' class='chkBox' /><label for='chkBoxID_"+i+"'> ChkBox "+i+"</label>"); //this is what I'm going to create 10 times   
       
       if(i<=5) { //just create 5 for the second fieldset
            var chBox_2 = $("<input type='checkbox' name='chkBoxGroup2' id='chkBoxID2_"+i+"' value='1' class='chkBox' /><label for='chkBoxID2_"+i+"'> ChkBox "+i+"</label>");
       }
       
        $('#f1').append(chBox); //append the new element to the page 
        $('#f2').append(chBox_2); //append the new element to the page 
   }  
});

  /*  $('.selectAll').click(function() { //select all function    
        var $chStatus = this.checked;  //set the status of the checkbox
        var $checkbox = $("input[name='chkBoxGroup']"); //reference to our group of checkboxes
        $('fieldset').find( $checkbox ).each(function() { //find each checkbox with the name chkBoxGroup           
            $(this).prop('checked', $chStatus);
        });
    });   
  */