Setting a column classname based on value of other column

Setting a column classname based on value of other column

dynasoftdynasoft Posts: 422Questions: 67Answers: 3

Hi
I need to do as per above. Can I return and set a different classname based on the value inside one of a DT's columns?
How can this be achieved? Is using the column render method best or can it be best done by iterating all rows via DT's preinit event and how is the column's classname set then?

Here's what I have:

                { data: null,
                    defaultContent: '',
                    orderable: false,
                    render: function ( data, type, row ) {

                        if (IsTransTypeInvoiceLike(data.TransType) == true)
                        {
                            //return and set classname, but how?
                        }
                    },
                    className: 'details-control'
                },

or,

        var table = $('#tblDataTable1').DataTable();
        $('#tblDataTable1')
            .on( 'init.dt', function () {
                table.rows().eq(0).each( function ( index ) {
                    var row = table.row( index );
                    var data = row.data();
                    if (IsTransTypeInvoiceLike(data.TransType) == true)
                    {
                            //return and set classname, but how?
                    }                        
                } );
        }).dataTable();

I'm setting a different classname for the 1st column in this example: https://datatables.net/blog/2019-01-11

Many thanks.

Answers

  • rf1234rf1234 Posts: 2,806Questions: 85Answers: 406
    edited April 2020

    I would use rowCallback because it is easier for this use case.
    https://datatables.net/reference/option/rowCallback

    Something like:

    $('#example').dataTable( {
      "rowCallback": function( row, data ) {
        if ( data.yourColumn == "A" ) {
          $('td:eq(4)', row).addClass("yourClass");
        }
      }
    } );
    

    'td:eq(4)' is the column you want to manipulate.

    Example from my own coding. Works like a charm for any kind of manipulation:

    rowCallback: function (row, data) {
        if ( $('td:eq(1)', row).text() <= '' && $('td:eq(0)', row).text() > '' ) {
            var msg = lang === 'de' ? 
                            "Bitte Wertebereich definieren! (Button rechts)" : 
                            "Please define value range!(button right)";
            $('td:eq(1)', row).html( '<span class="fontThick">' + msg + '</span>' );
        }
    }
    
  • dynasoftdynasoft Posts: 422Questions: 67Answers: 3

    Very helpful. Thanks a lot.

This discussion has been closed.