jQuery Datatables change value of a column based on condition
I have Datatables which is working fine. However I want to tweak it a bit. As you can see I have this condition:
if ( data.status == 0 )
Which means that if the status
is equal to zero I will make the text color red and green otherwise. However I also want to change the text of the data.status
Coz it is 0
or 1
. How can I make the text appear Pending
if zero and Approved
if 1.
<script>
$(document).ready(function(){
$('#LeaveList').DataTable({
processing: true,
serverSide: true,
ajax: 'leave-list',
"createdRow": function ( row, data, index ) {
if ( data.status == 0 ) {
$('td', row).eq(6).addClass('text-danger');
}
else
{
$('td', row).eq(6).addClass('text-success');
}
},
columns: [
{data: 'id', name: 'id'},
{data: 'employee_name', name: 'employee_name'},
{data: 'employee_id', name: 'employee_id'},
{data: 'from_date', name: 'from_date'},
{data: 'to_date', name: 'to_date'},
{data: 'leave_type', name: 'leave_type'},
// {data: 'department', name: 'department'},
{data: 'status', name: 'status'},
{data: 'created_at', name: 'created_at'},
{data: 'action', name: 'action', orderable: true, searchable: true}
]
});
});
</script>
I want to this in this jquery part not in the query of data
你可以使用fnCreateCell来修改你的数据。
$(document).ready(function(){
$('#LeaveList').DataTable({
processing: true,
serverSide: true,
ajax: 'leave-list',
columns: [
{data: 'id', name: 'id'},
{data: 'employee_name', name: 'employee_name'},
{data: 'employee_id', name: 'employee_id'},
{data: 'from_date', name: 'from_date'},
{data: 'to_date', name: 'to_date'},
{data: 'leave_type', name: 'leave_type'},
// {data: 'department', name: 'department'},
{data: 'status', name: 'status',
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
if (sData) {
$(nTd).addClass('text-success');
}else{
$(nTd).addClass('text-danger');
}
}
},
{data: 'created_at', name: 'created_at'},
{data: 'action', name: 'action', orderable: true, searchable: true}
]
});
});
Assume that your current code is working properly. Then you only need to modify the createdRow
part like so:
...
createdRow: function ( row, data, index ) {
if ( data.status == 0 ) {
$('td', row).eq(6).addClass('text-danger').text('Pending');
} else {
$('td', row).eq(6).addClass('text-success').text('Approved');
}
},
...
However, as pointed out by markpsmith, the cleaner way is to use the render
options. You may read about the columns.render
here.