Sorting column with numbers and text (dynamically added)

Sorting column with numbers and text (dynamically added)

Tosti911Tosti911 Posts: 2Questions: 0Answers: 0

Hi guys, been using datatables for some time, and for most cases, the documentation and the forum were enough to get going. But I've come to a standstill and after trying some possible solutions (which seem not to work?), I decided to ask for some help.

So the problem is: I'm having a table that has data added dynamically (ajax call to get the data, parse it and add it to the table). One column contains numbers and text (with html) which I would like to sort.
Code example here: https://live.datatables.net/mafexeqi/1/edit

My problem is that I can't figure out what I'm missing and why I can't sort only using the numbers and ignoring the string (html).
I've tried using the data-order= on its own but it did not work (example: https://live.datatables.net/wucugiri/1/edit )

I've also tried using the render: function() and removing all the non-numbers, but it also did not work (example: https://live.datatables.net/wajinuva/1/edit ). I've also tried using the columnDefs and creating a custom "date": function() with no success. I also gave natural.js a try but also without any results. I've also tried some other ideas given as answers here on the forum but it's the same output.

Maybe it has to do with the format of the numbers?

I am kinda out of options, maybe is there anyone who could give me some tips?

Replies

  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954

    I've tried using the data-order= on its own but it did not work

    The HTML5 orthogonal data options only work with HTML supplied data.

    I've also tried using the render: function()

    Datatables does automatic type detection, see the columns.type docs for details. Type detection still types the column as text. So you need to have Datatables adjust the type based on the orthogonal data by adjusting your if statement, like this if (type === 'sort' || type === 'type') {. See the updated example:
    https://live.datatables.net/jepaluyo/1/edit

    Another option might be the natural sorting plugin.

    Kevin

  • Tosti911Tosti911 Posts: 2Questions: 0Answers: 0

    Thank you for your answer Kevin, I tried something close to your example (but probably a little different) which did not work so it's good to see that I was close. After a few more hours, I managed to find a workaround which was pretty simple. I removed the HTML from the row add and used the render function to show it:

    if (type === 'sort') {
        return parseInt(data.replace(/\D/g,''));
    }
    if (type === 'display') {
        return data + "<sup>Text</sup></td>";
    }
    

    while also passing in the data-order= which seems to do the trick, example: https://live.datatables.net/hesaqano/1/edit

    Thank you again for your answer, it really helped me!

Sign In or Register to comment.