Format each row in a dynamic table using javascript - HTML - javascript

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');

Related

Trying to add a select element to a table dynamically but its not showing up in the cell

I've already managed to successfully insert various elements dynamically into separate cells of a table per row such as label, checkbox and input text type. However, when I try to insert a select element with the options it doesn't show up in the row and also, all the other elements stop appearing as well.
As you can see, I'm using Javascript HTML DOM to add (append) the elements to the parents - all elements appear in the respective cells per row up until I try to append the select element, then nothing shows in the table, no elememnts, no rows, cells, nothing.
Can anyone enlighten me here - is it a style problem?
Thanks.
Here is my CSS, HTML and SCRIPT codes as follows. Questions is a 2 dim array to populate the elements appended to the cells
function fillTable(questions) {
var questsLength = questions.length;
for (var i = 0; i < questsLength; i++) {
var row = document.createElement("tr");
row.setAttribute = ("id", i);
var col1 = document.createElement("td");
var col2 = document.createElement("td");
var col3 = document.createElement("td");
var col4 = document.createElement("td");
var qno = document.createElement("label");
qno.innerHTML = i + 1;
col1.appendChild(qno);
row.appendChild(col1);
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
col2.appendChild(checkbox);
row.appendChild(col2);
var question = document.createElement("input");
question.type = "text";
question.value = questions[i][1];
col3.appendChild(question);
row.appendChild(col3);
var questOpts = document.createElement("select");
var alphabet = ["A", "B", "C", "D", "E", "F"];
for (var j = 0; j < alphabet.length; j++) {
var option = document.createElement("option");
option.value = alphabet[j];
option.innerHTML = alphabet[j];
questOpts.appendChild(option);
}
col4.appendChild(questOpts);
row.appendChild(col4);
var tab = document.getElementById("bdy");
tab.appendChild(row);
}
}
.fixTableHead {
overflow-y: auto;
height: 110px;
position: relative;
top: 100px;
}
.fixTableHead th {
position: sticky;
top: 0;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 8px 15px;
border: 2px solid #529432;
background: #ffffff;
}
th {
background: #ABDD93;
}
<div class="fixTableHead">
<table id="bdy">
<tr>
<th>No</th>
<th>Select</th>
<th>Question</th>
<th>Answer options</th>
<th>Question type</th>
</tr>
</table>
</div>

How can we implement Pagination using Javascript in simple HTML page

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.

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!

I am trying to create a table of 8x8 squares in HTML using script

I thought maybe doing this with a for loop like that
<table>
<script>
for (var i; i = 0; i < 8; i++) {
document.write("<tr>")
for (var j; j = 0; j < 8; j++) {
document.write("<td></td>")
}
document.write("<tr>")
}
</script>
</table>
This code doesn't seem to work. Please understand that I am not at all fluent in js, so a solution with an explenationn will really help.
document.write would not work as you have tried here, it won't write the <tr> tags at the place you've mentioned either.
You need to modify the DOM, specifically the table element.
Below code, takes a reference of table and appends the 8 rows and 8 cols in it.
document.querySelector("table").innerHTML = new Array(8).fill("<tr>" + new Array(8).fill("<td></td>").join("") + "</tr>").join("");
td {
border: 1px solid;
padding: 5px;
}
<table></table>
PS: This is a basic example to get you started, there are better ways to achieve this. you should look more into DOM Manipulation in JS.
Use DOM manipulation methods and make sure to put <script> right before the closing tag of <body> instead of inside <tabl> , here is a working example:
let table = document.getElementById('table');
for (let i = 0; i < 8; i++) {
let row = document.createElement('TR');
table.appendChild(row);
for (let i = 0; i < 8; i++) {
var cell = document.createElement('TD');
row.appendChild(cell);
}
}
td {
border: 1px solid #333;
padding: 5px;
}
<table id="table"></table>
document.write() will never create a child element inside the <table> element, you can create a child element for a parent with appendChild().
Here an example with pure JavaScript:
for (var i = 0; i < 8; i++) {
var row = document.createElement("tr");
document.getElementById('tbl').appendChild(row).setAttribute("id", 'row_' + i);
for (var j = 0; j < 8; j++) {
var column = document.createElement("td");
document.getElementById('row_' + i).appendChild(column);
}
}
table {
border: 1px solid black;
}
td {
border: 1px solid blue;
padding: 3px;
margin: 2px;
}
<table id='tbl'></table>
Here, the script will create a child <tr> for the <table>, then you can create child <td> for the <tr>.

Create Recursive Form Elements

I'm creating a homework calculator. I need to recursively create form elements, and found out how to make a recursively creating table. How do I turn the spaces in that table into form elements that create themselves recursively? If this isn't clear, please tell me.
<table id="xTable"></table>
<script>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "I want to make this into a recursive form creator ";
}
}
</script>
<style>
td {
border: 2px ridge #333;
text-align: center;
}
</style>
It's rather simple, just create the elements you want to insert into the cells with document.createElement, then set the properties you want them to have and use cell.appendChild to place them into the cell.
This example creates <input type="text"> elements:
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
var input = document.createElement('input');
input.type = 'text';
input.name = 'input_r' + i + '-c' + j;
cell.appendChild(input);
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>

Categories

Resources