Shift+Click to Select/Deselect Checkboxes.


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

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.