Check/uncheck all checkboxes

Here is another useful jQuery snippet to check and uncheck all checkboxes.

Simple usage:

The HTML

<div class="options">
  <ul>
    <li><a href="#" class="check-all">Check All</a></li>
    <li><a href="#" class="uncheck-all">Uncheck All</a></li>
  </ul>

  <ul>
    <li><input type="checkbox" id="option1" /><label for="option1">Option 1</label></li>
    <li><input type="checkbox" id="option2" /><label for="option2">Option 2</label></li>
    <li><input type="checkbox" id="option3" /><label for="option3">Option 3</label></li>
    <li><input type="checkbox" id="option4" /><label for="option4">Option 4</label></li>
    <li><input type="checkbox" id="option5" /><label for="option5">Option 5</label></li>
  </ul>
</div>

The JS

$(function() {
  $('.check-all').live('click', function(){
    $(this).closest('.options').find('input[type=checkbox]').attr('checked', true);
    return false;
  });

  $('.uncheck-all').live('click', function(){
    $(this).closest('.options').find('input[type=checkbox]').attr('checked', false);
    return false;
  });
});

Demo

Advertisements

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