Multi-select with shift on HTML table

Well I was looking into adding a shift select on a checkbox table. After performing a quick search I found a jquery plugin. This was a great start, but I found it would not unselect successfully. I made some minor modifications and now it appears to work in IE9 and FF...

(function($){
  function toggleSelected(element, shouldSelect) {
    $(element).attr("checked", shouldSelect);
    if(shouldSelect){
        $(element).parents("tr").addClass("selected");
    } else {
        $(element).parents("tr").removeClass("selected");
    }
  }
 
  $.fn.shiftSelectTable = function(){
    var $table = $(this);
   
    $table.find(":checkbox").click(function(event){
      var last = $table.data("jquery-shift-select-table.last");
      $table.data("jquery-shift-select-table.last", $(this).get());
     
      if(last == null || !event.shiftKey) {
        $(this).parents("tr").toggleClass("selected");
      }
      else {
        var shouldSelect = $(this).attr("checked");
        if(shouldSelect===undefined){
            shouldSelect=null;
        }
        var $checkboxes = $table.find(":checkbox");
        var currentIndex = $checkboxes.index(this);
        var lastIndex = $checkboxes.index($(last));
        var $checkboxesToChange = (currentIndex >= lastIndex) ? $checkboxes.slice(lastIndex, currentIndex+1) : $checkboxes.slice(currentIndex, lastIndex+1);
       
        $checkboxesToChange.each(function(){
          toggleSelected(this, shouldSelect);
        });
      }
    });
   
    this.find(":checked").parents("tr").toggleClass("selected");

    return this;
  };
})(jQuery);

Comments

Popular posts from this blog

IE9 Intranet compatibility mode in Intranet websites

Intersystems Caché performance, woe is me...