Home > Net >  jQuery dataTables row.add with different classes on outer td based on content
jQuery dataTables row.add with different classes on outer td based on content

Time:03-08

I want to add entries to a jQuery Datatable with row.add and while adding (or afterwards if not possible while adding) change the class of the outer <td> based on the content. Values > 5 should get the class color-green, values below 5 color-red

var mTableROH   = $('.mm-table.ROH').DataTable(
    {
        dom: 'Bfrtip',
        "stateSave": true,

    }
);

for(let i = 0; i < 10; i  )
{
  mTableROH.row.add(
          [
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
          ]
  );
 
}
 mTableROH.columns.adjust().draw();

    
.color-red{
  color: red;
}

color-green{
  color: green;
}
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">

                            <table id="mm-table-roh" >
                                <thead>                             
                                    <tr>
                                        <th>Value 1</th>
                                        <th>Value 2</th>
                                        <th>Value 3</th>
                                        <th>Value 4</th>
                                        <th>Value 5</th>
                                        <th>Value 6</th>
                                        <th>Value 7</th>
                                        <th>Value 8</th>
        
                                    </tr>
                                </thead>
                                <tbody>
                                
                                </tbody>

                            </table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>

How to add those classes while adding new rows like this?

CodePudding user response:

So, here is an approach on how to tackle your problem. Get all your cells with document.querySelectorAll and then you should do a forEach method in order to get the innerHTML of every cell. Thus this will allow you to get the string and from there on you can do a parseFloat() method to get the real numeric value of the cell. At last, you can do a conditional statement which checks if the value is below or more than 5. If it is likewise, you assign the class with classList.add() inside every cell you need. Cheers

var mTableROH = $('.mm-table.ROH').DataTable({
  dom: 'Bfrtip',
  "stateSave": true,

});

for (let i = 0; i < 10; i  ) {
  mTableROH.row.add(
      [
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
      ]).draw()
    .nodes()
    .to$()
    .addClass('row');
}

mTableROH.columns.adjust().draw();
let cells = document.querySelectorAll("td");

cells.forEach(function(cell) {
    let value = parseFloat(cell.innerHTML);
    if(value > 5) {
       cell.classList.add("color-green");
     } else {
       cell.classList.add("color-red");
     }
});
.color-red {
  color: red;
}

.color-green {
  color: green;
}
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">

<table id="mm-table-roh" >
  <thead>
    <tr>
      <th>Value 1</th>
      <th>Value 2</th>
      <th>Value 3</th>
      <th>Value 4</th>
      <th>Value 5</th>
      <th>Value 6</th>
      <th>Value 7</th>
      <th>Value 8</th>

    </tr>
  </thead>
  <tbody>

  </tbody>

</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>

CodePudding user response:

While I'm at this let me also help you simplify your for loop so that you don't have to repeat (Math.random() * 10).toFixed(2) 8 times

for (let i = 0; i < 10; i  ) {
    let randomNumbers = [];
    for (let j = 0; j < 8; j  ) {
        randomNumbers.push((Math.random() * 10).toFixed(2));
    }
    mTableROH.row.add(randomNumbers)
}
mTableROH.columns.adjust().draw();

Right after the above code, you can write this, this adds the class after the adding of the table cells:

$(".mm-table.ROH tbody td").each(function() {
     const value = parseFloat($(this).text());
     $(this).addClass(value > 5 ? "color-green" : "color-red");
});

What it does is using the jQuery selector we can retrieve all the td elements inside the tbody of the element with class .mm-table.ROH, and using the .each() function, we pass in a function that gets executed for each td element. So we retrieve the value from the .text() property of $(this) (which refers to the current td element), and then add the corresponding class based on if the value is more than 5 or not.

CodePudding user response:

So after reading your comment I did more research and I think this is better since I believe you are concerned about performance:

var mTableROH = $('.mm-table.ROH').DataTable({
    dom: 'Bfrtip',
    "stateSave": true,
    "createdRow": function(row, data, dataIndex) { // add a callback function
        const length = row.children.length;
        for (let i = 0; i < length; i  ) {
            row.children[i].className = data[i] > 5 ? "color-green" : "color-red";
        }
    }
});

// Below remains the same as my previous answer
for (let i = 0; i < 10; i  ) {
    let randomNumbers = [];
    for (let j = 0; j < 8; j  ) {
        randomNumbers.push((Math.random() * 10).toFixed(2));
    }
    mTableROH.row.add(randomNumbers)
}
mTableROH.columns.adjust().draw();

Basically we can just add a createdRow (https://datatables.net/reference/option/createdRow) property inside the object argument of .DataTable() that is executed when a TR element is created (and all TD child elements have been inserted)

Also another change is this time it's replacing all the classes of the td elements instead of adding a class, if you just wanna add the class you can replace

row.children[i].className = data[i] > 5 ? "color-green" : "color-red";

with

row.children[i].classList.add(data[i] > 5 ? "color-green" : "color-red");
  • Related