public
Last active

jQuery plugin for shift + click to select multiple checkboxes

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Usage: $form.find('input[type="checkbox"]').shiftSelectable();
// replace input[type="checkbox"] with the selector to match your list of checkboxes
 
$.fn.shiftSelectable = function() {
var lastChecked,
$boxes = this;
 
$boxes.click(function(evt) {
if(!lastChecked) {
lastChecked = this;
return;
}
 
if(evt.shiftKey) {
var start = $boxes.index(this),
end = $boxes.index(lastChecked);
$boxes.slice(Math.min(start, end), Math.max(start, end) + 1)
.attr('checked', lastChecked.checked)
.trigger('change');
}
 
lastChecked = this;
});
};

Nice! I have wrote a jQuery plugin with that feature and some others: http://rmariuzzo.github.io/checkboxes.js/ Maybe it would be nice to work on together on it.

Thanks for this cool piece of code. I am using it together with jquery tablesorter. After sorting the table, range selector goes weird. How can I reset it so that I could run shiftSelectable() again after sorting? Thanks again.

Got it, insert this code on line 7:
$boxes.off('click');

I then run initialize the code as callback every time I sort the table.

var chkboxes = $('.chkbox');
chkboxes.click(function(e) {
if(!lastChecked) {
lastChecked = this;
return;
}

        if(e.shiftKey) {
            var start = $chkboxes.index(this);
            var end = $chkboxes.index(lastChecked);

            $chkboxes.slice(Math.min(start,end), Math.max(start,end)+ 1).attr('checked', lastChecked.checked);

        }

        lastChecked = this;
    });

What about this one?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.