jQuery Select All Checkboxes

I needed to come up with a generic way of checking all checkboxes that could be reused using jQuery. At first I thought about using the data- attribute to define which class of checkboxes to check. But then found a great way to just check all checkboxes that are located in their element container. (The .on method required jQuery 1.7)

HTML Example Code:

<div class="control-group">
<input type="checkbox" class="selAllChksInGroup"> All
<input type="checkbox" value="NE"> Nebraska
<input type="checkbox" value="FL"> Florida
</div>

JavaScript Code:

$(document).ready(function(){

$("input[type=checkbox].selAllChksInGroup").on("click.chkAll", function( event ){
    $(this).parents('.control-group:eq(0)').find(':checkbox').prop('checked', this.checked);
});

});
Advertisements