Skip to content
Advertisement

Datatables js: custom css

I’m using Datatables.js with Laravel. I’m post a request with ajax and I want to show the returned response in the table. Is there a way to customize this table? Can we customize the tags by giving them an id or class name? I tried this but didn’t get any results.

For example: I want to make the text color in the first column green or I want to add a photo next to the text in the second column.

$(function() {
  $("#ordersTable").DataTable({
    processing: true,
    serverSide: false,
    ajax: "{{route('index22')}}",
    
    data : [{"orderId":"1","orderNumber":"ABC123", "orderDate" : "12/Jun/2022"}],
    columns: [{
        data: 'orderId'
      },
      {
        data: 'orderNumber'
      },
      {
        data: 'orderDate'
      },
    ]
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>


<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">

<table id="ordersTable" class="table-striped table">
  <thead>
    <tr>
      <td>ORDER NUMBER</td>
      <td>STORE</td>
      <td>STATUS DATE</td>
    </tr>
  </thead>
</table>

Advertisement

Answer

You can change the text colour simply using css.

To add an image, you can add a custom render function as below:

$(function() {
  $("#ordersTable").DataTable({
    processing: true,
    serverSide: false,
    ajax: "{{route('index22')}}",
    
    data : [{"orderId":"1","orderNumber":"ABC123", "orderDate" : "12/Jun/2022"}, {"orderId":"2","orderNumber":"DEF987", "orderDate" : "11/Jun/2022"}],
    columns: [{
        data: 'orderId'
      },
      {
        data: 'orderNumber',
        render: function (data, type) 
        {
          if (type === 'display') 
          {
            return "<img src='https://via.placeholder.com/80x40.png?text=ORDER' />" + data;
          }
          
          return data;
         }
      },
      {
        data: 'orderDate'
      },
    ]
  });
});
#ordersTable tbody tr td:first-child
{
  color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>


<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">

<table id="ordersTable" class="table-striped table">
  <thead>
    <tr>
      <td>ORDER ID</td>
      <td>ORDER NUMBER</td>
      <td>ORDER DATE</td>
    </tr>
  </thead>
</table>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement