One way to do paging exclusively with jQuery / Javascript is to have the data in a Javascript vector and then apply it to a table with a specific function.
For example, you can use PHP to generate the following vector (or return it in JSON format in an Ajax call):
var dados = [
['Banana', '10,00'],
['Maça', '2,00'],
['Pera', '6,00'],
['Goiaba', '3,25'],
['Tamarindo', '1,50'],
['Cenoura', '0,75'],
['Alface', '0,99'],
['Tomate', '3,21'],
['Abacaxi', 'N/D'],
['Kiwi', '99,50'],
['Cebola', '1,15'],
['Alho', '1,02'],
['Abóbora', '4,75'],
['Pêssego', '2,33'],
['laranja', '2,99']
];
Then imagine a basic HTML containing an empty table and the forward and backward buttons as follows:
<table>
<thead>
<tr>
<th>Descrição</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2" align="center">Nenhum dado ainda...</td>
</tr>
</tbody>
</table>
<div>
<button id="anterior" disabled>‹ Anterior</button>
<span id="numeracao"></span>
<button id="proximo" disabled>Próximo ›</button>
</div>
Here you will need some Javascript elements to determine the data page size and what the current page is:
var tamanhoPagina = 6;
var pagina = 0;
It is also necessary to have a function to fill the data of the current page in the table and, as a bonus, to show the page number:
function paginar() {
$('table > tbody > tr').remove();
var tbody = $('table > tbody');
for (var i = pagina * tamanhoPagina; i < dados.length && i < (pagina + 1) * tamanhoPagina; i++) {
tbody.append(
$('<tr>')
.append($('<td>').append(dados[i][0]))
.append($('<td>').append(dados[i][1]))
)
}
$('#numeracao').text('Página ' + (pagina + 1) + ' de ' + Math.ceil(dados.length / tamanhoPagina));
}
It would be interesting to enable or disable the Próximo
and Anterior
buttons when on the last page or the first page, respectively. You could also disable it if you only had one page:
function ajustarBotoes() {
$('#proximo').prop('disabled', dados.length <= tamanhoPagina || pagina > dados.length / tamanhoPagina - 1);
$('#anterior').prop('disabled', dados.length <= tamanhoPagina || pagina == 0);
}
Finally, we need to put the event to go back and forth on the pages, as well as initialize all of this in loading the HTML page:
$(function() {
$('#proximo').click(function() {
if (pagina < dados.length / tamanhoPagina - 1) {
pagina++;
paginar();
ajustarBotoes();
}
});
$('#anterior').click(function() {
if (pagina > 0) {
pagina--;
paginar();
ajustarBotoes();
}
});
paginar();
ajustarBotoes();
});