/ 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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var lastChecked = null; var handleChecked = function(e) { if(lastChecked && e.shiftKey) { var i = $('input[type="checkbox"]').index(lastChecked); var j = $('input[type="checkbox"]').index(e.target); var checkboxes = []; if (j > i) { checkboxes = $('input[type="checkbox"]:gt('+ (i-1) +'):lt('+ (j-i) +')'); } else { checkboxes = $('input[type="checkbox"]:gt('+ j +'):lt('+ (i-j) +')'); } if (!$(e.target).is(':checked')) { $(checkboxes).removeAttr('checked'); } else { $(checkboxes).attr('checked', 'checked'); } } lastChecked = e.target; // Other click action code. } $('input[type=checkbox]').click(handleChecked);