TheFrack
TheFrack

Reputation: 2873

Datatables: Need to sort a column numerically by data in HTML

I have a table that looks like this...

<table id="myTable">
    <tr>
        <td><a href="site.com?id=1">1</a></td>
        <td>Foo</td>
    </tr>
    <tr>
        <td><a href="site.com?id=9">9</a></td>
        <td>Bar</td>
    </tr>
    <tr>
        <td><a href="site.com?id=10">10</a></td>
        <td>Baz</td>
    </tr>
</table>

I need to make it so my Bootstrap Datatables scripting will sort by the inner HTML of the anchor tag, and sort it numerically. Currently it is sorting it like this...

1   Foo
10  Baz
9   Bar

But I need it to be sorted like this...

1   Foo
9   Bar
10  Baz

I'm not really sure how to go about this. I have it sorting, but it thinks the inner HTML is a string, not a number :(

Upvotes: 1

Views: 2379

Answers (1)

bikedorkseattle
bikedorkseattle

Reputation: 981

I'm assuming you are generating your links server-side. You are better off rendering these on the client for two reasons:

  1. Your sort will work
  2. Your payload will be smaller

To do this you need to use aoColumnsDef and aTargets similar to the below

    "aoColumnDefs": [
    {
        "aTargets": [ 1 ],
        "fnRender": function ( o, val ) {
          var link = "<a class='' href='site.com?id=" + o.aData[0] + "'>" + o.aData[0] + "</a>";
          return link;
        }
    },

Hope this helps.

Upvotes: 2

Related Questions