Skip to content Skip to sidebar Skip to footer

Custom Sorting Of Jquery Datatable Columns

I have a table which contains columns of numbers and NA. NA1024<

Solution 1:

Simply use data-order attribute in <td> element. Plugin will sort based on that. For your case the HTML will be:

<tr><tddata-order="-1">NA</td></tr><tr><tddata-order="1024">1024</td></tr><tr><tddata-order="100">100</td></tr><tr><tddata-order="200">200</td></tr><tr><tddata-order="300">300</td></tr><tr><tddata-order="2096">2096</td></tr>

More HTML5 attributes are available to solve problems of filtering, sorting, searching, etc.

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

Solution 2:

By looking at the Numbers with HTML plugin you can take the existing code and modify the regex to look for negative numbers instead of stripping everything. Using that you can put together a HTML tag around the "NA" and use the HTML5 data-internalid to store the lowest number of the collection.

so it becomes:

<td><adata-internalid="-1">NA</a></td>

and (notice the regex)

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"num-html-pre": function ( a ) {
    var x = String(a).replace(/(?!^-)[^0-9.]/g, "");
    returnparseFloat( x );
},

"num-html-asc": function ( a, b ) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},

"num-html-desc": function ( a, b ) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}});

Then in the datatable, set the type to num-html

$('table').dataTable({
    "aoColumns": [{ "sType": "num-html" }],
    "aaSorting": [[ 0, "desc" ]],
});

You can see my full solution here: http://jsfiddle.net/rYtxh/4/

Post a Comment for "Custom Sorting Of Jquery Datatable Columns"