Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DataTable Grouping para Valmiki
<table class="dtable" class="display" style="width:100%">
<thead>
<tr>
<th>Dia</th>
<th>Descrição</th>
<th>Nome</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>Dia</th>
<th>Descrição</th>
<th>Nome</th>
</tr>
</tfoot>
</table>
$.ajax({
url: "//api.jsonbin.io/b/5b0daa76c83f6d4cc734a15f"
}).done(data => {
let tbody = $(".dtable tbody");
$.each(data.Titulo, (i, item) => {
$.each(item.Dias, (j, dia) => {
tbody.append(
`<tr><td>${dia.Data}</td><td>${dia.Descricao}</td><td>${
item.Nome
}</td></tr>`
);
});
});
let groupColumn = 2;
let table = $(".dtable").DataTable({
columnDefs: [{ visible: false, targets: groupColumn }],
order: [[groupColumn, "asc"]],
displayLength: 25,
drawCallback: function(settings) {
var api = this.api();
var rows = api.rows({ page: "current" }).nodes();
var last = null;
api
.column(groupColumn, { page: "current" })
.data()
.each(function(group, i) {
if (last !== group) {
$(rows)
.eq(i)
.before(
'<tr class="group"><td colspan="5">' + group + "</td></tr>"
);
last = group;
}
});
}
});
// Order by the grouping
$("#example tbody").on("click", "tr.group", function() {
var currentOrder = table.order()[0];
if (currentOrder[0] === groupColumn && currentOrder[1] === "asc") {
table.order([groupColumn, "desc"]).draw();
} else {
table.order([groupColumn, "asc"]).draw();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
tr.group,
tr.group:hover {
background-color: #ddd !important
}
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.