Search code examples
jqueryruby-on-railssortinghtml-tabletablesorter

Table sorter with delimiters rails


I have a table that has a column named Goal, that table gets filled with ruby like this:

<table  data-sorted="myTable">
  <thead>
    <tr>
      <th><a rel="tooltip" title="Name">Name</a></th>
      <th>subname</th>
      <th>Days</th>
      <th>%</th>
      <th>Goal</th>
      <th>achieved</th>
    </tr>
  </thead>
<tbody>
 <% @results.each do |id, rows| %>
 <% rows.each do |row| %>
    <tr>
      <td>
        <b><%= row[:name] %></b></td>
      <td><%= row[:subname] %></td>
      <td><%= row[:days] %></td>
      <td class="<%= status_indicator(row[:percentage].to_f) %>"><%= number_to_percentage(row[:percentage], :precision => 2)%></td>
      <td class="{sorter: 'thousands'}"="<%= row[:goal].to_i %>"><%=number_with_delimiter(row[:goal].to_i) %></td>
      <td class="achieved"><%= row[:achieved].to_i %></td>
    </tr>
  <% end %>
<% end %>
  </tbody>
</table>

according to my online research i have this on the jquery.

$.tablesorter.addParser({ 
    // set a unique id 
    id: 'thousands',
    is: function(s) { 
        // return false so this parser is not auto detected 
        return /^[0-9]?[0-9,\.]*$/.test(s);
    }, 
    format: function(s) {
        // format your data for normalization 
        return jQuery.tablesorter.formatFloat( s.replace(/,/g,'') );
    }, 
    // set type, either numeric or text 
    type: 'numeric' 
}); 

$(function() {
    $("[data-sorted=myTable]").tablesorter({
        headers: {
            6: {//zero-based column index
                sorter:'thousands'
            }
        }
    });
});

sorting works in all the columns of the table but on the ones that i have a thousand delimiter, i get this as a result

  1. this is how the table starts on load

this is how the table starts on load

  1. this is how the table renders when sorted

this is how the table renders when sorted


Solution

  • It looks like the headers option is assigning the "thousands" sorter to the 7th column (zero-based index)

    headers: {
        6: {//zero-based column index
            sorter:'thousands'
        }
    }
    

    Where as the meta-data is assigning it to the 5th column

    <td class="{sorter: 'thousands'}"...
    

    So either you need to add the meta-data plugin to make the class name work, or change your header option to target the proper column:

    headers: {
        4: {//zero-based column index
            sorter:'thousands'
        }
    }