Stackoverflow! I got a task to create sortable/dynamic table with options to add and remove content and I've managed to do it. My last task however is to make a pagination of 20 rows per page and that's where my 10 days Javascript knowledge is put to a high test. Namely, I can't even put my foot of the ground.
Can anyone help me out in understanding the logic behind the creation of pagination?
CodePudding user response:
here is the code for paginating your table for 20 elements per page:
Edit the function loadTableData() with this:
//Pagination
function loadTableData(movieData, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
var movieDatap = movieData.slice((page_number - 1) * page_size, page_number * page_size);
const tableBody = document.getElementById('tableData');
let txt = '';
for (let i = 0; i < movieDatap.length; i ) {
txt = txt `<tr><td>${movieDatap[i].name}</td>
<td>${movieDatap[i].genre}</td><td>${movieDatap[i].rating}</td>
<td><button onclick="deleteRow(${i});">Delete</button>
<button onclick="editRow(${i});">Edit</button></td></tr>`;
}
tableBody.innerHTML = txt;
}
function decreaseTableDatas(){
var value = parseInt(document.getElementById('pagenumber').value, 10);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('pagenumber').value = value;
loadTableData(movieData, 20, value);
}
function incrementTableDatas(){
var value = parseInt(document.getElementById('pagenumber').value, 10);
value = isNaN(value) ? 0 : value;
value ;
document.getElementById('pagenumber').value = value;
loadTableData(movieData, 20, value);
}
window.onload = () => {
loadTableData(movieData, 20, 1);
}
Update the HTML with this:
<div class="pagination">
<div class="pagination-block">
<span class="pageButton outline-none" onclick="decreaseTableDatas()" id="button_prev">Prev</span>
<input type="button" value="1" id="pagenumber" />
<span class="pageButton outline-none" onclick="incrementTableDatas()" id="button_next">Next</span>
</div>
</div>
I hope that is what you are looking for mate