1

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

3
  • This might be a duplicate post: stackoverflow.com/questions/10305552/… Commented Dec 10, 2012 at 21:28
  • According to the page you linked to, "Data can often be a complicated mix of numbers and letters (file names are a common example) and sorting them in a natural manner is quite a difficult problem. Fortunately a deal of work has already been done in this area by other authors - the following plug-in uses the naturalSort() function by Jim Palmer (download it here) to provide natural sorting in DataTables." It looks like that page lists various methods for handling that situation. Commented Dec 10, 2012 at 21:32
  • I'm assuming this is with server-side data? Commented Dec 11, 2012 at 0:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is useful, thanks, but it does not sort. Is it possible to have it both sort and render? I tried bSortable: true, but it does nothing.
Okay I figured it out, you need to use: bUseRendered : false Thanks!
This depends on the end user's browser - one of the beauties of DataTables is that it degrades gracefully - if JS is turned off on the browser, it will just display a standard HTML table. With your solution, the plain HTML table will not contain the links. This might also cause issues for robots crawling the page...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.