Checkbox Range Selection Update

Just a little update to my checkbox range selection jQuery plugin to allow chaining.  I'd forgotten to return 'this' at the end of the function.  Here's the full source, including the mod:

(function($) {
  $.fn.enableCheckboxRangeSelection = function() {
    var lastCheckbox = null;
    var $spec = this;
    $spec.bind("click", function(e) {
      if (lastCheckbox != null && e.shiftKey) {
        $spec.slice(
          Math.min($spec.index(lastCheckbox), $spec.index(e.target)),
          Math.max($spec.index(lastCheckbox), $spec.index(e.target)) + 1
        ).attr({checked: e.target.checked ? "checked" : ""});
      }
      lastCheckbox = e.target;
    });
    return $spec;
  };
})(jQuery);

You can check the project page as well, for full history and updates.

8 responses to “Checkbox Range Selection Update”

  1. Michael Heilemann

    I'm looking for just this block of code for use in Habari–short and sweet. Any chance you'll let me? :)

  2. Michael Heilemann

    Awesome, thank you.

  3. Richie

    Cheers mate. Very useful. Would never have thought to use splice.

  4. Dan

    Thanks for this, just to add though (And this is less efficient), my checkboxes have event handlers on them, so I have replaced the .attr calls with a filter and click functions. Works for me :)

    (function($) {
      $.fn.enableCheckboxRangeSelection = function() {
        var lastCheckbox = null;
        var $spec = this;
        $spec.bind("click", function(e) {
    
          if (lastCheckbox != null && e.shiftKey) {
            $spec.slice(
              Math.min($spec.index(lastCheckbox), $spec.index(e.target)),
              Math.max($spec.index(lastCheckbox), $spec.index(e.target)) + 1
            ).filter(e.target.checked ? ":not(:checked)" : ":checked").click();
          }
        });
        return $spec;
      };
    })(jQuery);
    
  5. Dan

    Yeah, I'll go with that; I suppose I used click because that's the event I bound to in my existing code, but change is more appropriate to what we are actually doing.

    I did notice a reduction of performance with this method (curiously this was very significant with Firebug enabled, FF3.5). This is mostly down to the time taken firing all those events rather than the filter operations as far as I can tell.

  6. Nirmalya

    Can someone make this in flex?? I mean, select checkbox range within a form. please help… thanks in advance