Skip to content

Instantly share code, notes, and snippets.

@mattyo161
Last active December 17, 2015 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattyo161/5526387 to your computer and use it in GitHub Desktop.
Save mattyo161/5526387 to your computer and use it in GitHub Desktop.
DataTables plug-in for supporting custom sorting of any data type using a simple comment prefix in the field. Place the sortable value using a string, float, integer or date to sort with. In the format <!-- CDX:<data> --> where "X" is "S" for string, "I" for Integer, "F" for Float, "D" for Date.
/* DataTables plug-in to allow for a custom Data Value for sorting based on a comment */
jQuery.fn.dataTableExt.aTypes.unshift(function(sData) {
/* Look for a special comment <!-- CDx:<data> --> if found then return that type */
if (sData.indexOf('<!-- CDI:') >= 0) {
return 'comment-dt-integer';
} else if (sData.indexOf('<!-- CDS:') >= 0) {
return 'comment-dt-string';
} else if (sData.indexOf('<!-- CDF:') >= 0) {
return 'comment-dt-float';
} else if (sData.indexOf('<!-- CDD:') >= 0) {
return 'comment-dt-date';
} else {
return null;
}
});
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"comment-dt-integer-pre": function(a) {
var sPos = a.indexOf('<!-- CDI:') + 9;
return parseInt(a.substr(sPos, a.indexOf(" -->", sPos) - sPos),10);
},
"comment-dt-integer-asc": function(a, b) {
return a - b;
},
"comment-dt-integer-desc": function(a, b) {
return b - a;
}
});
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"comment-dt-float-pre": function(a) {
var sPos = a.indexOf('<!-- CDF:') + 9;
return parseFloat(a.substr(sPos, a.indexOf(" -->", sPos) - sPos));
},
"comment-dt-float-asc": function(a, b) {
return a - b;
},
"comment-dt-float-desc": function(a, b) {
return b - a;
}
});
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"comment-dt-string-pre": function(a) {
var sPos = a.indexOf('<!-- CDS:') + 9;
return a.substr(sPos, a.indexOf(" -->", sPos) - sPos);
},
"comment-dt-string-asc": function(a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"comment-dt-string-desc": function(a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"comment-dt-date-pre": function(a) {
var sPos = a.indexOf('<!-- CDD:') + 9;
var d = Date.parse(a.substr(sPos, a.indexOf(" -->", sPos) - sPos));
if (isNaN(d)) {
return 0;
}
return d;
},
"comment-dt-date-asc": function(a, b) {
return a - b;
},
"comment-dt-date-desc": function(a, b) {
return b - a;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment