2

I am trying to sort a DataTable column based on a custom attribute that the column has. My table look like this:

<table class="dataTable">
  <thead>
    <tr>
      <th width="15%" scope="col" class="currency-field">${msg_amountLabel}</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-raw="${order.totalPrice}" class="order-history-list-price">${order.formattedPrice}</td>
    </tr>
    </tbody>
</table>

And my JS looks like this:

        jQuery.fn.dataTableExt.oSort["currency-desc"] = function (a, b) {

            return 1;
        };
        jQuery.fn.dataTableExt.oSort["currency-asc"] = function (a, b) {

            return 0;
        }

        tableObject.DataTable({
            "info": false,
            "paging": false,
            "order": orderObject,
            "columnDefs": [{
                    "targets"  : 'currency-field',
                    "type": "currency",
                    "data": "data-raw"
                }]
        });

For now I have dummy values in my sorters to test if they are being called, I was expecting to receive the element in the sorters but I receive only the value.

Is it possible to pass some parameter to the columnnDefs to infor that I want the value from the attribute data-raw? Or any other way to inform the dataTable sort to use the data-raw instead of the field value?

1 Answer 1

7

Instead of using data-raw you can use data-sort for configuration-by-convention; datatables will automatically pick this up and use it for the sort value with no need for any additional code on your part.

$(document).ready(function() {
  $('.dataTable').dataTable();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>

<table class="dataTable">
  <thead>
    <tr>
      <th style='text-align:left'>Sort Col</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-sort="1">First</td>
    </tr>
    <tr>
      <td data-sort="4">Fourth</td>
    </tr>
    <tr>
      <td data-sort="3">Third</td>
    </tr>
    <tr>
      <td data-sort="2">Second</td>
    </tr>
  </tbody>
</table>

Additional info: https://datatables.net/examples/advanced_init/html5-data-attributes.html

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.