Sort Columns with Numbers and Empty Cells
Sort Columns with Numbers and Empty Cells
josiahsavary
Posts: 2Questions: 0Answers: 0
I noticed that sorting cells numerically works pretty well unless you have empty cells mixed in with integers in your column. This plug-in makes sure that empty cells get sorted lower than 0.
jQuery.fn.dataTableExt.oSort['numWithNull-asc'] = function(a,b) {
var x = parseInt(a);
var y = parseInt(b);
return ((isNaN(x) || x < y) ? -1 : ((isNaN(y) || x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['numWithNull-desc'] = function(a,b) {
var x = parseInt(a);
var y = parseInt(b);
return ((isNaN(x) || x < y) ? 1 : ((isNaN(y) || x > y) ? -1 : 0));
};
jQuery.fn.dataTableExt.oSort['numWithNull-asc'] = function(a,b) {
var x = parseInt(a);
var y = parseInt(b);
return ((isNaN(x) || x < y) ? -1 : ((isNaN(y) || x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['numWithNull-desc'] = function(a,b) {
var x = parseInt(a);
var y = parseInt(b);
return ((isNaN(x) || x < y) ? 1 : ((isNaN(y) || x > y) ? -1 : 0));
};
This discussion has been closed.
Replies
Regards,
Allan
I've used the code above exactly as it is and the following to set up the table...
[code]
$(document).ready(function(){
$.extend( $.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline"
} );
jQuery.fn.dataTableExt.oSort['numWithNull-asc'] = function(a,b) {
var x = parseInt(a);
var y = parseInt(b);
return ((isNaN(x) || x < y) ? -1 : ((isNaN(y) || x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['numWithNull-desc'] = function(a,b) {
var x = parseInt(a);
var y = parseInt(b);
return ((isNaN(x) || x < y) ? 1 : ((isNaN(y) || x > y) ? -1 : 0));
};
$('#data_table').dataTable({
"sDom": "<'row'<'span11'f>r>t<'row'<'span3'l><'span8'p>>",
"sPaginationType": "bootstrap",
"iDisplayLength": 25,
"aoColumns": [
null,
null,
null,
{ "sType" : "numWithNull" },
null,
{ "sType" : "NumericOrBlank" },
null,
{ "sType" : "NumericOrBlank" },
null,
null,
null
]
});
});
[/code]
As you can see I also tried the NumericOrBlank code posted elsewhere on these forums...which resulted in erratic behavior with the empty cells.
Any ideas?
I use "?" for null values also. At last I found a method for it. I just changed parseInt to parseFloat for my float values column. Now everything works fine.
Thank you very much. You saved my day...
Like so:
[code]return ((isNaN(y) || x < y) ? -1 : ((isNaN(x) || x > y) ? 1 : 0));[/code]
http://datatables.net/forums/discussion/comment/27376#Comment_27376