How to add sorting indicators to a table?

Asked

Viewed 1,487 times

2

I created a [ascending - descending] sorting algorithm of [letters - numbers].

I’m trying to add some sort indicator in the column title, but it’s not working as it should.

Example:

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>

I am using the Font Awesome icons if possible reuse

2 answers

3


Right in function makeSortable() identifque o Indice "th" e faca ele receber as classes do font-awesome fa-caret-up e fa-caret-down according to type of ordering (ascending - descending) which is identified by the condition if((1 - dir) === 1) // ascendente else descendente.

Example:

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

You can use Datatables. It’s a very useful js library for any sort of sorting you need in your Datatables.

Follow an example:

<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>

Here the javascript to trigger the ordering:

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

And here it is:

ordenação datatables js

Back in the website of them has the complete documentation, strongly recommend.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.