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

Ravi picture Ravi · Mar 8, 2011 · Viewed 381.7k times · Source

I am trying to check/uncheck all checkboxes using jQuery. Now by checking/unchecking the parent checkbox all the child checkboxes are getting selected/deselected also with the text of parent checkbox getting changed to checkall/uncheckall.

Now I want to replace parent checkbox with an input button, and change the text also on the button to checkall/uncheckall. THere is the code, can anyone please tweak the code ?

    $( function() {
        $( '.checkAll' ).live( 'change', function() {
            $( '.cb-element' ).attr( 'checked', $( this ).is( ':checked' ) ? 'checked' : '' );
            $( this ).next().text( $( this ).is( ':checked' ) ? 'Uncheck All' : 'Check All' );
        });
        $( '.cb-element' ).live( 'change', function() {
            $( '.cb-element' ).length == $( '.cb-element:checked' ).length ? $( '.checkAll' ).attr( 'checked', 'checked' ).next().text( 'Uncheck All' ) : $( '.checkAll' ).attr( 'checked', '' ).next().text( 'Check All' );

        });
    });


   <input type="checkbox" class="checkAll" /> <b>Check All</b>

   <input type="checkbox" class="cb-element" /> Checkbox  1
   <input type="checkbox" class="cb-element" /> Checkbox  2
   <input type="checkbox" class="cb-element" /> Checkbox  3

Answer

Prakash picture Prakash · Mar 8, 2011

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