Add class to a column without affecting the header [DataTables.net]

1

I try to add a class to a column without having to affect the header but, I have not been able to achieve it, I have tried several things like.

This is what the API

says
"createdRow": function( row, data, dataIndex ) {
    if ( data[5] == "1" ) {
        $(row).addClass('badge badge-success');
}}

This second one is the one I'm using and it affects the whole column but I just want it to affect the td :

"columnDefs": [
    {
       targets: 5,
       className: 'badge badge-success',
    }
],

This is the result:

    
asked by J. Zambrano 23.10.2018 в 22:02
source

3 answers

0

To work with data cells only, use the function of createdCell (); Where this allows you to manipulate from the td tag.

columnDefs: [ {
    targets: 5,
    createdCell: function (td, cellData, rowData, row, col) {
       if ( cellData < 1 )
        $(td).addClass('badge badge-success');
    }
  } ]

To not affect the header, cellData is the index of when rendering; escape it.

    
answered by 23.10.2018 / 23:18
source
0

Try it with rowCallback like this:

$("#table").DataTable({
  'rowCallback': function(row, data, index){
    console.log(data[4]);
    if(data[4] == "1"){
      $(row).find('td:eq(4)').addClass('badge badge-success');
    }
  }
});
.badge {
  background-color: green;
}
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="table">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
    
answered by 23.10.2018 в 22:11
-1

IF WORK WITH DATA LOADED AFTER (as it can be database) the function works like this; for example in my case:

"rowCallback": function( row, data ) {
                if ( $('td:eq(5)', row).text() == "devolviendo") {
                  $('td:eq(5 )', row).addClass( 'clase_1' );
                }else if ( $('td:eq(5)', row).text() == "libre") {
                    $('td:eq(5 )', row).addClass( 'clase_2' );
                }
              }
answered by 24.10.2018 в 23:09