Reputation: 117
I have a DataTable with many columns of numbers. I thought it would be nice to colorize negative numbers so I added a render function, like this:
{ data: 'mynumbercolumn',
render: function(data, type, row) {
var x = row.mynumbercolumn;
if (x < 0)
x = '<span class="text-danger">' + x + '</span>';
return x;
}
},
It works in the sense that negative numbers have the text-danger class applied (ie they are in red) but now the column sorts in string order not numerical order, so like this:
1
1111
111111
2
222
Is there a way to add a class to a cell (or otherwise color negative numbers) in such a way that a numeric column will still sort numerically? If not I'll have to add a custom sort, I guess (or give up on the colorizing).
Upvotes: 2
Views: 298
Reputation: 85578
Take a look at the type
param https://datatables.net/reference/option/columns.render You return markup in any case, i.e regardless of the type
is filter
, display
, type
or sort. In this case you only want to return a formatted HTML-string on the type display
:
render: function(data, type, row) {
if (type === 'display') {
var x = row.mynumbercolumn;
if (x < 0) x = '<span class="text-danger">' + x + '</span>';
return x;
} else {
return data //or row.mynumbercolumn
}
}
A perhaps more elegant way could be to just style the <td>
itself in a
createdCell
callback. Something like :
createdCell: function (td, cellData, rowData, row, col) {
if (cellData < 0) {
$(td).addClass('text-danger')
}
}
Upvotes: 2