Client side sorting delle tabelle

Una volta che abbiamo ottenuto i nostri dati una tipica tabella si può presentare così in HTML:

<table class="sortable">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Author(s)</th>
<th>Publish&nbsp;Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="../covers/small/1847192386.png" width="49" height="61" alt="Building Websites with Joomla! 1.5 Beta 1" />
</td>
<td>Building Websites with Joomla! 1.5 Beta 1</td>
<td>Hagen Graf</td>
<td>Feb 2007</td>
<td>$40.49</td>
</tr>
<tr>
<td><img src="../covers/small/1904811620.png" width="49" height="61" alt="Learning Mambo: A Step-by-Step Tutorial to Building Your Website" /></td> <td>Learning Mambo: A Step-by-Step Tutorial to Building Your Website</td>
<td>Douglas Paterson</td>
<td>Dec 2006</td>
<td>$40.49</td>
</tr>
...
</tbody>
</table>

Ecco la nostra tabella sorting step 1

Ora vogliamo fare in modo che premendo su title gli item si riordino alfabeticamente. Assegnamo una classe alla nostra cella:

<thead>
<tr>
<th></th>
<th class="sort-alpha">Title</th>
<th>Author(s)</th>
<th>Publish&nbsp;Date</th>
<th>Price</th>
</tr>
</thead>

Ora un po' di javascript code:

$(document).ready(function() {
  $('table.sortable').each(function() {
    var $table = $(this);
    $('th', $table).each(function(column) {
      if ($(this).is('.sort-alpha')) {
		  $(this).addClass('clickable').hover(function() {
          $(this).addClass('hover');
        }, function() {
          $(this).removeClass('hover');
        }).click(function() {
          var rows = $table.find('tbody > tr').get();
          rows.sort(function(a, b) {
            var keyA = $(a).children('td').eq(column).text().toUpperCase();
            var keyB = $(b).children('td').eq(column).text().toUpperCase();
            if (keyA < keyB) return -1;
            if (keyA > keyB) return 1;
            return 0;
          });
          $.each(rows, function(index, row) {
            $table.children('tbody').append(row);
          });
        });
      }
    });
  });
});

I punti importanti del codice:

Ecco la nostra tabella sorting step 2

A questo punto però risistemando le colonne vado a perdere la sequenza dei loro colori, dunque devo resettarli

Javascript code:

$(document).ready(function() {
  var alternateRowColors = function($table) {
    $('tbody tr:odd', $table).removeClass('even').addClass('odd');
    $('tbody tr:even', $table).removeClass('odd').addClass('even');
  };
  $('table.sortable').each(function() {
    var $table = $(this);
    alternateRowColors($table);
    $('th', $table).each(function(column) {
      if ($(this).is('.sort-alpha')) {
        $(this).addClass('clickable').hover(function() {
          $(this).addClass('hover');
        }, function() {
                  $(this).removeClass('hover');
        }).click(function() {
          var rows = $table.find('tbody > tr').get();
          rows.sort(function(a, b) {
            var keyA = $(a).children('td').eq(column).text() 
                                                      .toUpperCase();
            var keyB = $(b).children('td').eq(column).text() 
                                                      .toUpperCase();
            if (keyA < keyB) return -1;
            if (keyA > keyB) return 1;
            return 0;
          });
          $.each(rows, function(index, row) {
            $table.children('tbody').append(row);
          });
          alternateRowColors($table);
        });
      }
    });
  });
});

Per questo mi sono costruito una funzione alternateRowColors

Ecco la nostra tabella sorting step 3

La stessa cosa potrebbe essere applicata agli altri campi, inoltre potremmo far ordinare i campi dal primo all'ultimo e dall'ultimo al primo in due direzioni, fino ad ottenere questo:

Ecco la nostra tabella sorting step 4