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.
JavaScript
x
19
19
1
$(function() {
2
$("#ordersTable").DataTable({
3
processing: true,
4
serverSide: false,
5
ajax: "{{route('index22')}}",
6
7
data : [{"orderId":"1","orderNumber":"ABC123", "orderDate" : "12/Jun/2022"}],
8
columns: [{
9
data: 'orderId'
10
},
11
{
12
data: 'orderNumber'
13
},
14
{
15
data: 'orderDate'
16
},
17
]
18
});
19
});
JavaScript
1
16
16
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
4
5
6
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
7
8
<table id="ordersTable" class="table-striped table">
9
<thead>
10
<tr>
11
<td>ORDER NUMBER</td>
12
<td>STORE</td>
13
<td>STATUS DATE</td>
14
</tr>
15
</thead>
16
</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:
JavaScript
1
28
28
1
$(function() {
2
$("#ordersTable").DataTable({
3
processing: true,
4
serverSide: false,
5
ajax: "{{route('index22')}}",
6
7
data : [{"orderId":"1","orderNumber":"ABC123", "orderDate" : "12/Jun/2022"}, {"orderId":"2","orderNumber":"DEF987", "orderDate" : "11/Jun/2022"}],
8
columns: [{
9
data: 'orderId'
10
},
11
{
12
data: 'orderNumber',
13
render: function (data, type)
14
{
15
if (type === 'display')
16
{
17
return "<img src='https://via.placeholder.com/80x40.png?text=ORDER' />" + data;
18
}
19
20
return data;
21
}
22
},
23
{
24
data: 'orderDate'
25
},
26
]
27
});
28
});
JavaScript
1
4
1
#ordersTable tbody tr td:first-child
2
{
3
color:green;
4
}
JavaScript
1
16
16
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
4
5
6
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
7
8
<table id="ordersTable" class="table-striped table">
9
<thead>
10
<tr>
11
<td>ORDER ID</td>
12
<td>ORDER NUMBER</td>
13
<td>ORDER DATE</td>
14
</tr>
15
</thead>
16
</table>