How do I check/uncheck all checkboxes with a button using jQuery?

Try this one :

$(document).ready(function(){
    $('.check:button').toggle(function(){
        $('input:checkbox').attr('checked','checked');
        $(this).val('uncheck all');
    },function(){
        $('input:checkbox').removeAttr('checked');
        $(this).val('check all');        
    })
})

DEMO


This is the shortest way I've found (needs jQuery1.6+)

HTML:

<input type="checkbox" id="checkAll"/>

JS:

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});

I'm using .prop as .attr doesn't work for checkboxes in jQuery 1.6+ unless you've explicitly added a checked attribute to your input tag.

Example-

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#">
    <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
    
    <fieldset>
        <legend>Loads of checkboxes</legend>
        <p><label><input type="checkbox" /> Option 1</label></p>
        <p><label><input type="checkbox" /> Option 2</label></p>
        <p><label><input type="checkbox" /> Option 3</label></p>
        <p><label><input type="checkbox" /> Option 4</label></p>
    </fieldset>
</form>

Try This One:

HTML

<input type="checkbox" name="all" id="checkall" />

JavaScript

$('#checkall:checkbox').change(function () {
   if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
   else $('input:checkbox').removeAttr('checked');
});​

DEMO


Html

<input type="checkbox" name="select_all" id="select_all" class="checkAll" />

Javascript

    $('.checkAll').click(function(){
    if($(this).attr('checked')){
        $('input:checkbox').attr('checked',true);
    }
    else{
        $('input:checkbox').attr('checked',false);
    }
});

Solution for toggling checkboxes using a button, compatible with jQuery 1.9+ where toogle-event is no longer available:

$('.check:button').click(function(){
      var checked = !$(this).data('checked');
      $('input:checkbox').prop('checked', checked);
      $(this).val(checked ? 'uncheck all' : 'check all' )
      $(this).data('checked', checked);
});

DEMO