2

Criei um algoritmo de ordenação [ascendente - descendente] de [letras - números].

Estou tentando adicionar algum indicador de ordenação no titulo das colunas, mas não esta funcionando como deveria.

Exemplo:

function sortTable(table, col, reverse) {
  var tb = table.tBodies[0],
    tr = Array.prototype.slice.call(tb.rows, 0),
    i;
  reverse = -((+reverse) || -1);
  var str1;
  var str2;
  tr = tr.sort(function(a, b) {
    if (a.cells[col].children[0] === undefined) {
      str1 = a.cells[col].textContent.trim();
      str2 = b.cells[col].textContent.trim();
    } else {
      str1 = a.cells[col].getElementsByTagName(a.cells[col].children[0].tagName)[0].value;
      str2 = b.cells[col].getElementsByTagName(a.cells[col].children[0].tagName)[0].value;
    }

    if (!isNaN(str1)) {
      if (str1.length === 1) {
        str1 = '0' + str1;
      }
      if (str2.length === 1) {
        str2 = '0' + str2;
      }
    }
    return reverse * (str1.localeCompare(str2));
  });
  for (i = 0; i < tr.length; ++i)
    tb.appendChild(tr[i]);
}

function makeSortable(table) {
  var th = table.tHead,
    i;
  th && (th = th.rows[0]) && (th = th.cells);
  if (th)
    i = th.length;
  else
    return;
  while (--i >= 0)
    (function(i) {
      var dir = 1;
      th[i].addEventListener('click', function() {
        sortTable(table, i, (dir = 1 - dir));
      });
    }(i));
}

function makeAllSortable(parent) {
  parent = parent || document.body;
  var t = parent.getElementsByTagName('table'),
    i = t.length;
  while (--i >= 0) {
    if (t[i].attributes['data-sortable'] !== undefined) {
      makeSortable(t[i]);
    }
  }
}
makeAllSortable();
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table class="table table-bordered table-responsive" data-sortable>
  <thead>
    <tr>
      <th>Código</th>
      <th>Nome</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>A - POSTO ASXL</td>
    </tr>
    <tr>
      <td>2</td>
      <td>B - POSTO BSP</td>
    </tr>
    <tr>
      <td>3</td>
      <td>AA - POSTO XYZ</td>
    </tr>
  </tbody>
</table>

Detalhe estou utilizando os icons da Font Awesome caso seja possível reaproveitar

2 Respostas 2

3

Bem na função makeSortable() identifque o indice "th" e faca ele receber as classes do font-awesome fa-caret-up e fa-caret-down conforme tipo de ordenação (ascendente - descendente) que é identificado pela condição if((1 - dir) === 1) // ascendente else descendente.

Exemplo:

function sortTable(table, col, reverse) {
  var tb = table.tBodies[0],
    tr = Array.prototype.slice.call(tb.rows, 0),
    i;
  reverse = -((+reverse) || -1);
  var str1;
  var str2;
  tr = tr.sort(function(a, b) {
    if (a.cells[col].children[0] === undefined) {
      str1 = a.cells[col].textContent.trim();
      str2 = b.cells[col].textContent.trim();
    } else {
      str1 = a.cells[col].getElementsByTagName(a.cells[col].children[0].tagName)[0].value;
      str2 = b.cells[col].getElementsByTagName(a.cells[col].children[0].tagName)[0].value;
    }

    if (!isNaN(str1)) {
      if (str1.length === 1) {
        str1 = '0' + str1;
      }
      if (str2.length === 1) {
        str2 = '0' + str2;
      }
    }
    return reverse * (str1.localeCompare(str2));
  });
  for (i = 0; i < tr.length; ++i)
    tb.appendChild(tr[i]);
}

function makeSortable(table) {
  var th = table.tHead,
    i;
  th && (th = th.rows[0]) && (th = th.cells);
  if (th)
    i = th.length;
  else
    return;
  while (--i >= 0)
    (function(i) {
      var dir = 1;
      $(th[i]).append('  <i class="fa fa-caret-up  hidden" data-order="up"></i>');
      $(th[i]).append('  <i class="fa fa-caret-down hidden" data-order="down"></i>');
      th[i].addEventListener('click', function() {
        sortTable(table, i, (dir = 1 - dir));
        if ((1 - dir) === 1) {
          $(th).find('i[data-order=down],i[data-order=up]').addClass('hidden');
          $(th[i]).find('i[data-order=up]').removeClass('hidden');
        } else {
          $(th).find('i[data-order=down],i[data-order=up]').addClass('hidden');
          $(th[i]).find('i[data-order=down]').removeClass('hidden');
        }
      });
    }(i));
}

function makeAllSortable(parent) {
  parent = parent || document.body;
  var t = parent.getElementsByTagName('table'),
    i = t.length;
  while (--i >= 0) {
    if (t[i].attributes['data-sortable'] !== undefined) {
      makeSortable(t[i]);
    }
  }
}
makeAllSortable();
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table class="table table-bordered table-responsive" data-sortable>
  <thead>
    <tr>
      <th>Código</th>
      <th>Nome</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>A - POSTO ASXL</td>
    </tr>
    <tr>
      <td>2</td>
      <td>B - POSTO BSP</td>
    </tr>
    <tr>
      <td>3</td>
      <td>AA - POSTO XYZ</td>
    </tr>
  </tbody>
</table>

1

Você pode usar o DataTables. É uma biblioteca de js muito útil para todo tipo de ordenação que você precisar em suas tables.

Segue um exemplo:

<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
        </tr>
    </tbody>
</table>

Aqui o javascript pra acionar a ordenação:

$(document).ready(function() {
$('#example').DataTable();
} );

E aqui como fica:

ordenação datatables js

Lá no site deles tem a documentação completa, recomendo fortemente.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .