jQuery - check, uncheck, invert checkboxes
Copy this code and paste it in your HTML
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js" language="javascript"></script> <script type="text/javascript" language="javascript"> $( function() {
$( '.checkAll' ).live( 'change', function() {
$( '.cb-element' ).attr( 'checked', $( this ).is( ':checked' ) ? 'checked' : '' );
$( this ).next().text( $( this ).is( ':checked' ) ? 'Uncheck All' : 'Check All' );
});
$( '.invertSelection' ).live( 'click', function() {
$( '.cb-element' ).each( function() {
$( this ).attr( 'checked', $( this ).is( ':checked' ) ? '' : 'checked' );
}).trigger( 'change' );
});
$( '.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' );
});
});
<span><input type="checkbox" class="checkAll" /> <b>Check All
</b> <span> or
<span><a href="javascript:void(0);" class="invertSelection">Invert Selection
</a></span> <span><input type="checkbox" class="cb-element" /> Checkbox 1
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 2
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 3
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 4
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 5
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 6
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 7
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 8
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 9
</span> <span><input type="checkbox" class="cb-element" /> Checkbox 10
</span>
Report this snippet
Comments
Subscribe to comments