jQuery Select All Checkboxes

Posted: February 16, 2012 in JavaScript

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
Comments
  1. Michael Zock says:

    Interesting. I usually tend to use something based on http://api.jquery.com/jQuery.each/

    • Mitch McKenzie says:

      This should work using $.each (pardon the formatting):

      $(function() {

      $(‘.selAllChksInGroup’).on(“click”,

      function(){

      $(this).siblings(“:checkbox”).each(function(){

      $(this).prop(“checked”,$(this).siblings(“:first”).prop(“checked”));

      });
      });
      });

      • Michael Zock says:

        That’s certainly a valid solution.

        On second thought, I would’ve chosen something that’s a bit more verbose, but easier to maintain: http://jsfiddle.net/J4kJy/

        Of course, this could easily be rewritten to use on() instead, in order to allow for dynamically added checkboxes.

  2. dai says:

    my search is finally over! thank you Chris. simple and dynamic.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s