JSFiddle - React, Tailwind, and code Playground
by Marcos vini
HTML
<input type="search" class="filtro-tabela" data-table="table" placeholder="Procurar">
<table class="table">
<thead>
<tr>
<th>Data</th>
<th>N° Pedido</th>
<th>Cliente</th>
</tr>
</thead>
<tbody>
<tr>
<td>09/04/2018</td>
<td>85331</td>
<td>João Batista</td>
</tr>
<tr>
<td>09/04/2017</td>
<td>85331</td>
<td>Pedro Emanuel</td>
</tr>
<tr>
<td>15/01/2018</td>
<td>98531</td>
<td>Jose Neto</td>
</tr>
<tr>
<td>09/04/2018</td>
<td>331</td>
<td>Ariel</td>
</tr>
</tbody>
</table>
CSS
table {
empty-cells: show;
border: 1px solid #cbcbcb
}
th, td {
border: none;
text-align: left;
padding: 12px;
}
tr {
border-bottom: 1px solid #ddd;
}
thead tr th {
display: table-cell;
text-align: center;
padding: 16px 10px;
font-weight: 600;
vertical-align: middle;
font-size: 0.8rem;
background: #f4f3f8;
cursor: pointer;
}
JavaScript
var Arr =Array.prototype;
var $input;
DATATABLE = {
ordenartodos: function(e){
var t = document.getElementsByClassName('table'), i = t.length;
while (--i >= 0) DATATABLE.criarordem(t[i]);
},
criarordem: function(table){
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; //se nenhum `<thead>` então não fizer nada
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {DATATABLE.ordenartabela(table, i, (dir = 1 - dir))});
}(i));
},
ordenartabela: function(table, col, reverse){
var tb = table.tBodies[0], // use `<tbody>` para ignorar `<thead>` e `<tfoot>`
tr = Array.prototype.slice.call(tb.rows, 0), // colocar linhas no array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // ordenar linhas
return reverse // `-1 *` se quiser ordem oposta
* (a.cells[col].textContent.trim() // usando `.textContent.trim ()` para teste
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // anexe cada linha em ordem
}
,
detectar_input: function(e){
$input = e.target;
var tables = document.getElementsByClassName($input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, DATATABLE.filtros);
});
});
},
filtros: function(row){
var text = row.textContent.toLowerCase(), val = $input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
},
init: function() {
var inputs = document.getElementsByClassName('filtro-tabela');
Arr.forEach.call(inputs, function(input) {
input.oninput = DATATABLE.detectar_input;
});
}
}
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
DATATABLE.init();
DATATABLE.ordenartodos();
}
});