0

When we build the HTML on server-side and only then apply DataTables, we can place the raw data in data-sort attribute and the formatted value on the cell's text, and it will properly sort the column.

I'm in such need, but data is coming as json, and I'm adding it as DataTable({data: object}).

I'm using columnDefs-render to format those values, and as we know DataTables uses the rendered string instead of raw data to sort.

I'd need some columnDefs setting to provide the raw data for sorting, but can't find how. Any ideas?

3
  • 2
    You can add data-sort as an attribute using jQuery. If that doesn't sound like a viable option, please update your question and show us how you're datatable is defined / setup. Commented Mar 26, 2020 at 20:19
  • Where can that be done? could you point an example? Commented Apr 1, 2020 at 14:41
  • 1
    You can research for how to add a data attribute using jQuery. Commented Apr 1, 2020 at 17:11

1 Answer 1

2

I figured it out!

1) On the web service response, make sure there's a field with the proper data type to be used on the sorting. In case (not best practice) the data is being formatted to string on the application and not by DataTables, add a field for the formatted string and another field for the proper data type

2) On DataTables settings, columns area, set as usual the proper column linked to the proper field

3) if DataTables is responsible for formatting, as usual, add the render setting for doing it

4) back to the columns area, add a new column on the end of the list, linked to the proper data type field, and add visible: false to it, this way this column will be available for other settings and functions to use, but won't be rendered visually

5) on columnDefs area, add { "orderData": 8, "targets": 5 }, this way when the column 5 is ordered, DataTables will use column 8 instead to do it, being column 8 the new invisible column added on (4)

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

Comments

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.