How can we implement Pagination using Javascript in simple HTML page - javascript

I'm trying to create an HTML table with pagination. I am calling a JSON data using a GET api and binding it as a dynamic table format. Pagination is handling in API by passing the page number. How can we simply handle the pagination in HTML Page with JS.
<!DOCTYPE html>
<html>
<head>
<title>Parent Child Mapping</title>
<style>
th,
td,
p,
input {
font: 14px Verdana;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight: bold;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
<div id="" class="pager-nav"></div>
</body>
<script>
function CreateTableFromJSON() {
var xhttp = new XMLHttpRequest();
var myBooks = [];
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
myBooks = JSON.parse(xhttp.responseText);
console.log("ok" + myBooks);
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myBooks.length; i++) {
for (var key in myBooks[i]) {
console.log("myBooks..", myBooks[i])
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
};
xhttp.open("GET", "http://localhost:3000/", true);
xhttp.send();
}
</script>
</html>
This is the html code i have added for dynamic table.

You can create a row of buttons under your dynamic table, each of which correspond to the page number of results in your API.
Set an onclick event on the buttons to execute a GET request to your API with the correct parameters i.e. pageNumber, resultsPerPage -- this depends on how the API is set up.
Then you are effectively doing the same thing you are doing now, but with specific results based on page number and number of results/rows per page.
You can also cache the results to avoid further round trips on subsequent clicks of a previously clicked page number.

Related

Create HTML Table Using JSON data in JavaScript

I am still suffering with JavaScript as I am newbie so please be patient to me and guide me step by step .. and please don't overload the comments with links because this made me lost
This is the try to bypass the CORS problem
<!DOCTYPE html>
<html>
<head>
<title>Read data from External JSON file using JavaScript</title>
<style>
* { font:17px 'Segoe UI'; }
table, th, td {
border: solid 1px #ddd;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<h3>
Data extracted from External JSON file and converted to an HTML table
</h3>
<div id='showTable'></div>
</body>
<script>
// Create XMLHttpRequest object.
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://www.encodedna.com/library/sample.json";
fetch(proxyurl + url)
.then(response => response.text())
.then(contents => createTableFromJSON(contents))
.catch(() => console.log("No Access " + url + " Response. Blocked By Browser?"))
//var oXHR = new XMLHttpRequest();
// Initiate request.
//oXHR.onreadystatechange = reportStatus;
//oXHR.open("GET", "https://www.encodedna.com/library/sample.json", true); // get json file.
//oXHR.send();
// Create an HTML table using the JSON data.
function createTableFromJSON(jsonData) {
var arrBirds = [];
arrBirds = JSON.parse(jsonData); // Convert JSON to array.
var col = [];
for (var i = 0; i < arrBirds.length; i++) {
for (var key in arrBirds[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// Create a dynamic table.
var table = document.createElement// Create table header.
var tr = table.insertRow(-1); // Table row.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // Table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
// Add JSON to the table rows.
for (var i = 0; i < arrBirds.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrBirds[i][col[j]];
}
}
// Finally, add the dynamic table to a container.
var divContainer = document.getElementById("showTable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
};
</script>
</html>
I am getting No access ..
How can I read the JSON data and then convert to HTML table?
You got a couple of problems, but not with the CORS, you got the results from the request. The error came from the createTableFromJSON function.
The main problems:
Forgot to add ("table") after createElement
Two unnecessary loops
Wrong use of the JSON to get the Name
More tr than needed
Working code:
// Create XMLHttpRequest object.
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://www.encodedna.com/library/sample.json";
fetch(proxyurl + url)
.then(response => response.text())
.then(contents => createTableFromJSON(contents))
.catch((e) => console.log('error'))
// Create an HTML table using the JSON data.
function createTableFromJSON(jsonData) {
var arrBirds = [];
arrBirds = JSON.parse(jsonData); // Convert JSON to array.
var col = [];
for (var key in arrBirds) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
// Create a dynamic table.
var table = document.createElement("table") // Create table header.
var tr = table.insertRow(-1); // Table row. (last position)
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // Table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
tr = table.insertRow(-1); // add new row for the names
// Add JSON to the table rows.
for (var i = 0; i < arrBirds.length; i++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrBirds[i].Name;
}
// Finally, add the dynamic table to a container.
var divContainer = document.getElementById("showTable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
};
* {
font: 17px 'Segoe UI';
}
table,
th,
td {
border: solid 1px #ddd;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight: bold;
}
<h3>
Data extracted from External JSON file and converted to an HTML table
</h3>
<div id='showTable'></div>
I hope this helps!

Change the Title of Elements on a Table

I'm currently using the following code to create a table based on a JSON API. I want to change the title of the table columns to be Name and Score instead of userName and userScore...
I have tried adjusting the forEach statement that creates the table columns, but that didn't work...
axios
.get("[ip censored]/scores")
.then(function(response) {
let sortedList = response.data.sort((a, b) => b.userScore - a.userScore);
console.warn(sortedList);
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < sortedList.length; i++) {
for (var key in sortedList[i]) {
if (
col.indexOf(key) === -1 &&
(key === "userName" || key === "userScore")
) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < sortedList.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = sortedList[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("leaderboard");
divContainer.innerHTML = "";
divContainer.appendChild(table);
})
.catch(function(error) {
console.error(error);
});
I also tried using CSS to make the tables look prettier, but it still didn't work.
Given you know the incoming key names and that they're consistent a simple inline if/else in your JavaScript should be all you need.
Try this:
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER
// This inline if says if col[i] is userName then set innerHTML to Name, else Score
th.innerHTML = col[i]==='userName' ? 'Name' : 'Score';
tr.appendChild(th);
}
Never mind, I figured it out. I used an if statement, and if col[i] equaled the value I wanted, I changed the value before I pushed the table.
You can use an if statement.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
var heading = "";
if(col[i] == "userName"){
th.innerHTML = "Name";
}
else if(col[i] == "userScore"){
th.innerHTML = "Score";
}
tr.appendChild(th);
}

Returning Id of cell when clicked Javascript

I'm working on creating a table of cells that will change color when each cell is clicked on.
I've created the table and have unique Ids for 'td' element - how do I return the Id of the cell that was clicked so that I can change its background color?
Is it possible to do this with pure JS?
const grid = function makeGrid() {
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
var tblBody = document.createElement('tbody');
for (let i = 0; i < 5; i++) {
let row = document.createElement('tr');
for (j = 0; j < 5; j++) {
var cell = document.createElement('td')
row.appendChild(cell)
cell.setAttribute('id', 'makeId' + i + j);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl)
}
grid();
Rather than set event listeners on every single td element, use event delegation.
Set a listener on the table body. It will hear the clicks on the td elements. Use the event object's target property to determine which td was clicked. That is the one the change:
document.querySelector('tbody').addEventListener('click', (e)=>{
e.target.style.backgroundColor = 'pink';
}
You need to bind the click event to the created cell
EDITED: using Event delegation
tblBody.addEventListener('click', (e)=>{
if (e.target.nodeName.toUpperCase() === 'TD') {
console.log(e.target.id)
e.target.classList.add('bg');
}
});
const grid = function makeGrid() {
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table')
var tblBody = document.createElement('tbody')
tblBody.addEventListener('click', (e)=>{
if (e.target.nodeName.toUpperCase() === 'TD') {
console.log(e.target.id)
e.target.classList.add('bg');
}
});
for (let i = 0; i < 5; i++) {
let row = document.createElement('tr')
for (let j = 0; j < 5; j++) {
var cell = document.createElement('td')
cell.innerHTML = 'makeId' + i + j;
row.appendChild(cell)
cell.setAttribute('id', 'makeId' + i + j);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl)
}
grid();
.bg {
background-color: lightgreen;
}
<div id="pixelCanvas">
</div>
As suggested by Randy, rather than put a listener on every TD you can use event delegation and put the listener on a suitable ancestor, either a parent table section (tbody, thead, tfoot) or the table itself. Then use the event object passed to the listener to get the target of the event. If it's not a TD, go up the parent nodes until you reach a TD.
There is now Element.closest implemented in most browsers in use, but not IE. So you might want to use a polyfill or simple "upTo" function for those users.
Also, you can take advantage of the insertRow and insertCell methods of table and table section elements rather than the more long winded createElement. Lastly, you can combine creating the element and appending it in one go.
Anyhow, like this:
// Create a table with rows rows and cells columns
function genTable(rows, cells) {
var table = document.createElement('table');
// Create tbody and append in one go
var tbody = table.appendChild(document.createElement('tbody'));
tbody.addEventListener('click',highlightCell);
var row, cell;
// Use insert methods for less code
for (var i=0; i<rows; i++) {
row = tbody.insertRow();
for (var j=0; j<cells; j++) {
cell = row.insertCell();
cell.textContent = 'row ' + i + ' cell ' + j;
}
}
// Add entire table to document in one go, easier on host
document.body.appendChild(table);
}
// Highlight cell that was clicked on
function highlightCell(e){
// Remove highlight from all cells that have it
document.querySelectorAll('.highlight').forEach(
node => node.classList.remove('highlight')
);
// Add highlight to cell of td in which event occurred
var cell = e.target.closest('td');
cell.classList.add('highlight');
}
window.onload = function(){genTable(3, 3);};
table {
border-collapse: collapse;
border-left: 1px solid #bbbbbb;
border-top: 1px solid #bbbbbb;
}
td {
border-right: 1px solid #bbbbbb;
border-bottom: 1px solid #bbbbbb;
}
.highlight {
background-color: red;
}

Format each row in a dynamic table using javascript - HTML

im creating a dynamic table in a html form using the next function:
<script>
function poblarTabla() {
// CREATE DYNAMIC TABLE.
var table = document.createElement('table');
// SET THE TABLE ID.
// WE WOULD NEED THE ID TO TRAVERSE AND EXTRACT DATA FROM THE TABLE.
table.setAttribute('id', 'tablaDeCuentas');
var arrHead = new Array();
arrHead = ['Emp. ID', 'Emp.Name', 'Designation'];
var arrValue = new Array();
arrValue.push(['1', 'Green Field', 'Accountant']);
arrValue.push(['2', 'Arun Banik', 'Project Manager']);
arrValue.push(['3', 'Dewane Paul', 'Programmer']);
var tr = table.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th'); // TABLE HEADER.
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
for (var c = 0; c <= arrValue.length - 1; c++) {
tr = table.insertRow(-1);
for (var j = 0; j < arrHead.length; j++) {
var td = document.createElement('td'); // TABLE DEFINITION.
td = tr.insertCell(-1);
td.innerHTML = arrValue[c][j]; // ADD VALUES TO EACH CELL.
}
}
document.body.appendChild(table);
}
</script>
This works correctly, what i want to do now is format each row using this format:
<tr align="left" valign="middle"><td bgcolor="#005C84" width="240" height="30"> <p style="color: white; font-size: 14px;font-family: Arial,sans-serif;font-weight: normal;text-decoration: none; display:block; padding:0; margin:0; margin-left:10px">ID de cuenta:</p></td><td bgcolor="#e5f0c3"><p style="color: #666; font-size: 14px;font-family: Arial,sans-serif;font-weight: normal;text-decoration: none; display:block; padding:0; margin:0; margin-left:10px"></p></td></tr>
So each time that a row is created, is displayed in the form with this format. Can anyome give me a hand? Thnks in advance!
Instead of using inline styles, you can try creating classes and then add them as you like while you are creating the table or its rows.
style.css
.table-style{
align: left;
valign: middle;
}
then in your javascript:
table.classList.add('table-style');

test.html:208 Uncaught ReferenceError: createtable is not defined

Ive been trying to make a webpage that can read an excel file and then create a table out of it. I already got the table generating part to work, but I can't get the loading part to work. I am getting an error that says that my function is not defined.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table Example</title>
</script> -->
</head>
<body>
<script type="text/javascript" src="http://cdn.jsdelivr.net/alasql/0.3/alasql.min.js">
var myBooks
function createtable(){
(function () {
'use strict';
}
}
}
alasql('SELECT * FROM XLSX("test.xlsv")').then(function(data){
myBooks = console.log(data);
});
angular
.module('jfy')
.factory('ImportExportToExcel', ImportExportToExcel);
function ImportExportToExcel(alasql, $log, $rootScope) {
return {
importFromExcel: function (event) {
if (event.target.files.length == 0) {
return false;
}
alasql('SELECT * FROM FILE("test.xlsv",{headers:true})', [event], function (data) {
$rootScope.$broadcast('import-excel-data', data);
});
},
exportToExcel: function (fileName, targetData) {
if (!angular.isArray(targetData)) {
$log.error('Can not export error type data to excel.');
return;
}
alasql('SELECT * INTO XLSX("' + fileName + '.xlsx",{headers:true}) FROM ?', [myBooks]);
}
}
}
})();
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myBooks.length; i++) {
for (var key in myBooks[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
object.onclick = function(){table};
}
</script>
<input type="button" onclick="createtable()" value="Create Table From JSON" />
<div id="showData"></div>
</body>
</html>

Categories

Resources