Posted By

ReedD19 on 10/03/12


Tagged

form jquery checkbox gmail checkboxes multi-select shift+click multiple-select


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jmiller


Shift+Click to Select/Deselect Checkboxes.


 / Published in: JavaScript
 

Allows you to click a given checkbox X, then shift click another checkbox Y. All checkboxes between X and Y will be checked or unchecked based on the state of checkbox Y. i.e. if you're unchecking Y all boxes between X and Y will also be unchecked.

  1. var lastChecked = null;
  2. var handleChecked = function(e) {
  3. if(lastChecked && e.shiftKey) {
  4. var i = $('input[type="checkbox"]').index(lastChecked);
  5. var j = $('input[type="checkbox"]').index(e.target);
  6. var checkboxes = [];
  7. if (j > i) {
  8. checkboxes = $('input[type="checkbox"]:gt('+ (i-1) +'):lt('+ (j-i) +')');
  9. } else {
  10. checkboxes = $('input[type="checkbox"]:gt('+ j +'):lt('+ (i-j) +')');
  11. }
  12.  
  13. if (!$(e.target).is(':checked')) {
  14. $(checkboxes).removeAttr('checked');
  15. } else {
  16. $(checkboxes).attr('checked', 'checked');
  17. }
  18. }
  19. lastChecked = e.target;
  20.  
  21. // Other click action code.
  22.  
  23. }
  24. $('input[type=checkbox]').click(handleChecked);

Report this snippet  

You need to login to post a comment.