Let’s assume the cell of the Datatable are rendered like this:
columnDefs: [
{
targets: 0,
type: 'percent',
render: function (data, type, full, meta) {
let html = '<span class="sort-value">' + data + '</span>';
html += "(<span class='sort-percent'>" + full.percent + "</span>%)";
return html;
}
}
}
-
At this time, by clicking on the header, I want to sort in the ASC direction for the first sorting using the value with the
sort-value
class name of the rendered HTML element. -
The second sort is the same, but the DESC direction by the value with the
sort-value
class name. -
For the third sort, I want to sort in the ASC direction by the value with the
sort-percent
class name. -
For the fourth sort, I want to sort in the DESC direction by the value with the
sort-percent
class name.
Then I want to repeat this sequence over and over again.
So I created the logic for this and introduced the following two variables:
var previously_sorted_index = 0;
var sort_state = 0; // 0: default, 1: sort-value ASC, 2: sort-value DESC, 3: percentage ASC, 4: percentage DESC
And whenever the header is clicked and sort is performed, the sort_state
value is updated and this works well. For better understanding, here is my code:
$('#table thead th').on('click', function() {
var colIdx = $(this).index();
if(previously_sorted_index == colIdx) {
sort_state ++;
if(sort_state == 5)
sort_state = 1;
} else {
previously_sorted_index = colIdx;
sort_state = 1;
}
});
The problem is that I customized the sort using datatable’s sort plugin, but it doesn’t work as expected.
It simply performs a string sort using the HTML elements of the cell.
Here is my custom code
$.extend($.fn.dataTableExt.oSort, {
"percent-pre": function (a) {
let div = document.createElement('div');
div.innerHTML = a;
let sort_val_el = div.getElementsByClassName("sort-value");
let sort_percent_el = div.getElementsByClassName("sort-percent");
let sort_val = parseFloat(sort_val_el.length > 0 ? sort_val_el[0].innerHTML : 0);
let percentage_val = parseFloat(sort_percent_el.length > 0 ? sort_percent_el[0].innerHTML : 0);
return [sort_val, percentage_val];
},
"percent-asc": function (a, b) {
if(sort_state == 1) {
return a[0] > b[0] ? 1 : -1;
} else if(sort_state == 3) { // percentage ASC/DESC
return a[1] > b[1] ? 1 : -1;
}
return 0;
},
"percent-desc": function (a, b) {
if (sort_state == 2) { // sort-value ASC/DESC
return b[0] > a[0] ? 1 : -1;
} else if(sort_state == 4) { // percentage ASC/DESC
return b[1] > a[1] ? 1: -1;
}
return 0;
}
});
I debugged it, and the value of sort_state
is updated exactly as expected.
When percent-pre
returns a single value rather than an array as in my code (for example, only the percent
value), the sort works exactly based on that value.
If return an array and sorting by the value of any element of the array according to the sort_state
value does not work.
Is there something wrong with my code?
Thank you!