Adding classes to individual rows

Adding classes to individual rows

EricCEricC Posts: 2Questions: 1Answers: 0

I have a DataTable that is initialized via Ajax. I have been trying to apply a specific class following initialization to rows based on a status column, e.g. if the status is "Complete", add the class "legend-complete" to the row. I am successful with the click of a button, but I'd like to have it occur after the datatable loads. I haven't found a way or an event to do this. Is anyone able to point me in the right direction? My logic says it should go in the ready function, and though it triggers, it doesn't work.

Here is the simplified code:

    $(document).ready(function () {
        $('#statusTable').DataTable( {
            "ajax": {"url":"getstatus.php","dataSrc": "data"},
            "columns": [ 
                { "data": "client"},  
                { "data": "status" },   
            ],
            rowId: 'Rowid'
        });
        $('#statusTable').DataTable().columns.adjust().draw();
        $('#statusTable tr:contains("Complete")').addClass('legend-complete');
    });

    $.extend( true, $.fn.dataTable.defaults, {
        //responsive: true,
        lengthChange: false,
        header: false,
        scrollY: '50vh',
        scrollX: true,
        scrollCollapse: true,
        paging: false,
        destroy: true,
        "processing": true,
        select: 'single', 
        info: false,
        searching: false,
        "autoWidth": false
    } );

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949
    edited October 2023 Answer ✓

    This example shows how to add classes based on cell content. Change the selector used to add the class to the row, for example:

    $(row).addClass('legend-complete');
    

    I am successful with the click of a button, but I'd like to have it occur after the datatable loads.

    The problem with the above is ajax is an asynchronous process so lines 10 and 11 run before Datatables has initialization completed. Move the code into initComplete which runs after Datatables has completely initialized.

    The other issue is line 11 will only find the rows displayed on the page. Datatables removes the other rows so jQuery won't find them. createdRow is a better option.

    Another option using Datatables API's is rows().nodes(), something like this to search all rows in the table:

    table.rows('tr:contains("Complete")')
      .nodes()
      .to$()
      .addClass('legend-complete');
    

    This replaces line 11.

    Kevin

  • EricCEricC Posts: 2Questions: 1Answers: 0

    Thank you so much Kevin, that worked perfectly!

Sign In or Register to comment.