jQuery - check, uncheck, invert checkboxes


/ Published in: HTML
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js" language="javascript"></script>
  2. <script type="text/javascript" language="javascript">
  3. $( function() {
  4. $( '.checkAll' ).live( 'change', function() {
  5. $( '.cb-element' ).attr( 'checked', $( this ).is( ':checked' ) ? 'checked' : '' );
  6. $( this ).next().text( $( this ).is( ':checked' ) ? 'Uncheck All' : 'Check All' );
  7. });
  8. $( '.invertSelection' ).live( 'click', function() {
  9. $( '.cb-element' ).each( function() {
  10. $( this ).attr( 'checked', $( this ).is( ':checked' ) ? '' : 'checked' );
  11. }).trigger( 'change' );
  12. });
  13. $( '.cb-element' ).live( 'change', function() {
  14. $( '.cb-element' ).length == $( '.cb-element:checked' ).length ? $( '.checkAll' ).attr( 'checked', 'checked' ).next().text( 'Uncheck All' ) : $( '.checkAll' ).attr( 'checked', '' ).next().text( 'Check All' );
  15. });
  16. });
  17. </script>
  18. <div class="controls">
  19. <span><input type="checkbox" class="checkAll" /> <b>Check All</b> <span> or
  20. <span><a href="javascript:void(0);" class="invertSelection">Invert Selection</a></span>
  21. </div>
  22. <div class="elements">
  23. <span><input type="checkbox" class="cb-element" /> Checkbox 1</span>
  24. <span><input type="checkbox" class="cb-element" /> Checkbox 2</span>
  25. <span><input type="checkbox" class="cb-element" /> Checkbox 3</span>
  26. <span><input type="checkbox" class="cb-element" /> Checkbox 4</span>
  27. <span><input type="checkbox" class="cb-element" /> Checkbox 5</span>
  28. <span><input type="checkbox" class="cb-element" /> Checkbox 6</span>
  29. <span><input type="checkbox" class="cb-element" /> Checkbox 7</span>
  30. <span><input type="checkbox" class="cb-element" /> Checkbox 8</span>
  31. <span><input type="checkbox" class="cb-element" /> Checkbox 9</span>
  32. <span><input type="checkbox" class="cb-element" /> Checkbox 10</span>
  33. </div>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.