Easy Sort Html Table / Grid View using JQuery example

1st u need the gloruis sortElements by James Padolsey (well after getting JQ) 
http://james.padolsey.com/javascript/sorting-elements-with-jquery/

now grid views gives us a row with TH and the rest r TD so we need:
1 - take all the TRs
2 - build the compare callback func
3 - make it skip the TH
4 - be able to sort desc

so here, i put this just after James's code:

function MakeTableSortable(tableID) {
  $("#" + tableID + " th").click(function () {
    var index = this.cellIndex;
    if (this.abc == null) {
      this.abc = true;
    }             else {
      this.abc = !this.abc;
    }

    $(
"#" + tableID + " tr").sortElements(function (a, b) {
      if (a.cells[0].tagName == "TH" || b.cells[0].tagName == "TH") {
        return 0;
      }       var _a = a.cells[index].innerText.toLowerCase();
      var _b = b.cells[index].innerText.toLowerCase();
      if (!a.parentNode.rows[0].cells[index].abc) {
        if (_a > _b) return -1;
        if (_a < _b) return 1;
        return 0;
      }       if (_a > _b) return 1;
      if (_a < _b) return -1;
      return 0;
    });
  });
}


1 - take all the TRs - by puttign the id and after that an element tag name u get all the childs with that tag name, it can work with name just dont put '#'
2 - build the compare callback func - that is this part (comaring the string values):
      var _a = a.cells[index].innerText.toLowerCase();...
      if (_a > _b) return 1;...
3 - make it skip the TH - if tagName == 'TH' - case sensitive
4 - be able to sort desc - all the abc part, its just a flag in the TH

p.s. - if u add this on James's .js file u now only need to add a ref for it in any html doc and u have ur talbes auto sortable :)

window.onload = function () {
  var tables = document.getElementsByTagName("table");
  for (var i = 0; i < tables.length; i++) {
    MakeTableSortable(tables[i].id);
  }
}


see also http://bresleveloper.blogspot.co.il/2012/10/advanced-htmltable-gridview-auto-sort.html
example with the advanced sort http://jsbin.com/agijer/2/edit

Comments

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

Asp.Net Ending Response options, Response.End() vs CompleteRequest()

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem