Reputation: 90
I am designing a screen and wanted to show some tabular data using datatable and wanted to show table header with sub header as shown below:
Below are html and JS which I am using:
var datatbl = [
{id:1,name:"Deepak",location:"Surat",gender:"male", col:"red", dob:"07/02/1994"},
{id:2,name:"Ajinkya",location:"KP",gender:"male", col:"red", dob:"07/02/1994"},
{id:3,name:"Purv",location:"Ahm",gender:"male", col:"red", dob:"07/02/1994"},
{id:4,name:"Amol",location:"Pune",gender:"male", col:"red", dob:"07/02/1994"},
];
$(document).ready(function() {
$('#example').DataTable( {
data: datatbl,
sWidth:"800px",
columns: [
{ title:"ID",data: "id",name:"id",visible:false },
{ title:"Name",data: "name",name:"name",width:"30%" },
{ title:"Location",data: "location" },
{ title:"Gender",data: "gender" },
{ title:"Color",data: "col" },
{ title:"Date Of Birth",data: "dob" },
],
} );
} );
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<table id="example" class="display nowrap cell-border"></table>
</body>
</html>
Is there any plugin or quick way to get the desired output.
Upvotes: 1
Views: 2866
Reputation: 72165
You don't need a plugin to do this. Just use simple html to explicitly create the header:
var datatbl = [{
id: 1,
name: "Deepak",
location: "Surat",
gender: "male",
col: "red",
dob: "07/02/1994"
},
{
id: 2,
name: "Ajinkya",
location: "KP",
gender: "male",
col: "red",
dob: "07/02/1994"
},
{
id: 3,
name: "Purv",
location: "Ahm",
gender: "male",
col: "red",
dob: "07/02/1994"
},
{
id: 4,
name: "Amol",
location: "Pune",
gender: "male",
col: "red",
dob: "07/02/1994"
}
];
$(document).ready(function() {
$('#example').DataTable({
data: datatbl,
sWidth: "800px",
columns: [{
title: "ID",
data: "id",
name: "id",
visible: false
}, {
title: "Name",
data: "name",
name: "name",
width: "30%"
}, {
title: "Location",
data: "location"
}, {
title: "Gender",
data: "gender"
}, {
title: "Color",
data: "col"
}, {
title: "Date Of Birth",
data: "dob"
}, ],
});
}
);
th {
border-top: 1px solid #aaaaaa;
border-bottom: 1px solid #aaaaaa;
border-right: 1px solid #aaaaaa;
}
th:first-child {
border-left: 1px solid #aaaaaa;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<table id="example" class="display nowrap cell-border">
<thead>
<tr>
<th colspan=3>Basic info</th>
<th colspan=3>Additional data</th>
</tr>
<tr>
<th></th>
<th>Name</th>
<th>Location</th>
<th>Gender</th>
<th>Color</th>
<th>Date of Birth</th>
</tr>
</thead>
</table>
</body>
</html>
Upvotes: 1