jqueryjquery-pluginstablesorter

Is there a way to tell jQuery tablesorter that the table is already sorted?


I've a web app that builds a table from data it receives from an API. These data are a CSV string, which has its rows already sorted by the API using a couple of columns.

Currently, I use the sortList option with the same columns, ie, I have tablesorter doing the same sorting, despite this wouldn't be necessary, just to see the order ticks (down/up arrows) next to the column names.

Is there a way to tell tablesorter that the table is already sorted, including the columns? This would only be needed to show those header ticks.


Solution

  • You could just change the CSS class of the column(s) that are already sorted.

    Here's a demo where the first column already sorted is ascending order. When initializing the table the class "tablesorter-headerAsc" is added so that an upward arrow is shown.

    $("table thead tr:first th:first").addClass("tablesorter-headerAsc");
    

    (the JQuery selector $("table thead tr:first th:first") selects the first column in the first row of thead)

    Demo:

    $(function() {
      $("#myTable")
        .tablesorter();
      $("table thead tr:first th:first").addClass("tablesorter-headerAsc");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!-- choose a theme file -->
    <link rel="stylesheet" href="https://bowercdn.net/c/jquery.tablesorter-2.15.2/css/theme.default.css">
    <!-- load jQuery and tablesorter scripts -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js"></script>
    
    
    
    <table id="myTable" class="tablesorter">
      <thead>
        <tr>
          <th>Last Name</th>
          <th>First Name</th>
          <th>Email</th>
          <th>Due</th>
          <th>Web Site</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Bach</td>
          <td>Frank</td>
          <td>fbach@yahoo.com</td>
          <td>$50.00</td>
          <td>http://www.frank.com</td>
        </tr>
        <tr>
          <td>Conway</td>
          <td>Tim</td>
          <td>tconway@earthlink.net</td>
          <td>$50.00</td>
          <td>http://www.timconway.com</td>
        </tr>
        <tr>
          <td>Doe</td>
          <td>Jason</td>
          <td>jdoe@hotmail.com</td>
          <td>$100.00</td>
          <td>http://www.jdoe.com</td>
        </tr>
        <tr>
          <td>Smith</td>
          <td>John</td>
          <td>jsmith@gmail.com</td>
          <td>$50.00</td>
          <td>http://www.jsmith.com</td>
        </tr>
    
    
    
      </tbody>
    </table>

    Of course this trick should be used with caution, as you can never be sure the data is already sorted unless you sort it.

    Related question: jQuery Tablesorter: How to detect if column is already sorted?