Search code examples
javascriptsortingfootable

Stopping a row from being sorted via the sorting plugin


I have data in a footable table. The first row (tr) has averages for each row underneath. Example:

| Name    | Number |
--------------------
| Average | 4.5    |
| Jim     | 5.0    |
| Sam     | 4.0    |

The average row shouldn't be sorted, is there a class or attribute to prevent the average value from being sorted?


Solution

  • Because the default sort plugin does not support per row settings, you will need to hack your logic in, using custom sorter and custom marker.

    $('table').footable({
       sorters : {
          alpha : function mysorter ( a, b ) {
             if ( ! mysorter.top ) {
                mysorter.top = $('table .footable-sorted-desc').length ? 1 : -1;
                setTimeout( function(){ mysorter.top = 0; }, 0 );
             }
             if ( a.indexOf( '\u2063' ) >= 0 ) return mysorter.top;
             if ( b.indexOf( '\u2063' ) >= 0 ) return -mysorter.top;
             return a > b ? 1 : ( a < b ? -1 : 0 );
          }
       }
    });
    <link href="http://fooplugins.com/footable/css/footable.core.min.css" rel="stylesheet"/>
    <link href="http://fooplugins.com/footable/css/footable.metro.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://fooplugins.com/footable/js/footable.js"></script>
    <script src="http://fooplugins.com/footable/js/footable.sort.js"></script>
    
    <table><thead><tr><th>Name<th data-sort-initial="true">Number</thead><tbody>
    <tr><td>Average<td>4.5&#x2063;</tr>
    <tr><td>Jim<td>5.0</tr>
    <tr><td>Sam<td>4.0</table>

    Here I am using the Invisible Separator \u2063 to mark the 'top' content.

    A few extra lines are used to optimally detect sorting direction and adjust the result accordingly (smallest when ascending, largest when descending).