Per selezionare e deselezionare tutte le caselle con jQuery è veramente molto semplice. Qui di sequito un piccolo esempio di codice html e javascritp per meglio comprendere il funzionamento e il suo utilizzo.
Codice Html
<div class="controlli"> <span><input type="checkbox" class="checkAll" /> <b>Seleziona tutti</b> </span> oppure <span><a href="javascript:void(0);" class="invertSelection">Inverti Selezione</a></span> </div> <div class="elementi"> <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> </div>
Codice Javascript
<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' ) ? 'Deseleziona Tutti' : 'Seleziona Tutti' ); }); $( '.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( 'Deseleziona Tutti' ) : $( '.checkAll' ).attr( 'checked', '' ).next().text( 'Seleziona Tutti' ); }); }); </script>
Requisiti: jQuery
Demo: http://www.web-developers.it/demo/checkall.html