How to remove last header from the table in Javascript - javascript

I wrote a code to load data, adding and removing appended columns. However I am not able to remove the last header (of appended column). I managed to figure out to remove the first column header. Please see testing function. Is there a way to remove one cell header or removing a column with a header? The command
tbl.removeChild(tbl.firstChild);
removes only the first header of the first column. However, the code
tbl.removeChild(tbl.lastChild);
removes all data instead last header of the last appended column. What I am missing here?
Update: I managed to remove the last header but only once, next last column is removed but the header stay. Still, I am not able to solve the glitch. The code I modified is marked
Below is the complete code,
var flag1 = false;
var file = document.getElementById('inputfile');
var txtArr = [];
if (typeof(document.getElementsByTagName("table")[0]) != "undefined") {
document.getElementsByTagName("table")[0].remove();
}
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table"),
thead = document.createElement('thead');
var tblBody = document.createElement("tbody");
file.addEventListener('change', () => {
var fr = new FileReader();
fr.onload = function() {
// By lines
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
txtArr.push(lines[line].split(" "));
}
}
fr.readAsText(file.files[0]);
});
//console.log(flag1);
// document.getElementById('output').textContent=txtArr.join("");
//document.getElementById("output").innerHTML = txtArr[0];
// console.log(txtArr[2]);
function generate_table() {
// creating all cells
if (flag1 == false) {
th = document.createElement('th'),
th.innerHTML = "Name";
tbl.appendChild(th);
th = document.createElement('th');
th.innerHTML = "Sample1";
tbl.appendChild(th);
tbl.appendChild(thead);
tbl.appendChild(tblBody);
} //endif flag1=false
else {
th = document.createElement('th');
th.innerHTML = "Sample2";
tbl.appendChild(th);
tbl.appendChild(thead);
tbl.appendChild(tblBody);
}
for (var i = 0; i < txtArr.length - 1; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode(txtArr[i][j]);
cell.appendChild(cellText);
row.appendChild(cell);
tblBody.appendChild(row);
}
flag1 = true;
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
txtArr = [];
}
/////////// testing problems here /////////////////////
function testing() {
var i;
var lastCol = tbl.rows[0].cells.length - 1,
i, j;
// delete cells with index greater then 0 (for each row)
console.log(tbl.rows.length);
//while (tbl.hasChildNodes()) {
// tbl.removeChild(tbl.lastChild); // this line does not remove the last header
//}
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > lastCol - 1; j--) {
tbl.rows[i].deleteCell(j);
}
}
tbl.removeChild(thead); // this was updated
tbl.removeChild(th); // this was updated
// tbl.removeChild(tbl.firstChild); // this code remove only the first header
}
/////////// end of testing ////////////////////////////
function appendColumn() {
var i;
th = document.createElement('th');
th.innerHTML = "Sample";
tbl.appendChild(th);
tbl.appendChild(thead);
tbl.appendChild(tblBody);
// open loop for each row and append cell
for (i = 0; i < tbl.rows.length; i++) {
createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
}
}
// create DIV element and append to the table cell
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode(text); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('class', style); // set DIV class attribute
div.setAttribute('className', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
// delete table column with index greater then 0
function deleteColumn() {
var lastCol = tbl.rows[0].cells.length - 1,
i, j;
// delete cells with index greater then 0 (for each row)
console.log(tbl.rows.length);
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > lastCol - 1; j--) {
tbl.rows[i].deleteCell(j);
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Read Text File</title>
</head>
<body>
<input type="file" name="inputfile" id="inputfile">
<br>
<pre id="output"></pre>
<input type="button" value="Generate a table." onclick="generate_table()">
<input type="button" value="Add column" onclick="appendColumn()">
<input type="button" value="Delete column" onclick="deleteColumn()">
<input type="button" value="testing" onclick="testing()">
<table id="table">
</body>
</html>

You can loop over the rows and delete the last cell of each one.
for(const row of tbl.rows){
row.deleteCell(-1);
}
//or
[...tbl.rows].forEach(row => row.deleteCell(-1));

Related

Dynamically created html table data not showing in order as expected

function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "31";
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var thead = document.createElement('td');
thead.classList.add("ui-droppable");
thead.appendChild(data[j]);
tre.appendChild(thead);
tbody.appendChild(tre);
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>
I'm trying to order the data that I get from my server to match the columns of my table.
My table columns are days from Monday to Sunday. When my data has more than 7items it needs to separate with another td. The td shows me week 1 and when my data has more than 7 items it needs to separate again that shows week 2 etc.
Update
Im now using a snipped verdion of my code.
Hope someone can help me out with this.
Thank you
There's a few things going on in the code that are problematic.
An attempt to add the table cells to the row, and the row to the table, was made on each iteration of the for loop. That would have produced a lot of rows with single cells had it worked.
It didn't work because there was only ever a single instance of tre, the row variable. So that meant the line tbody.appendChild(tre); did nothing, since appendChild won't append an element that already has a parent element.
Because your data was an array of references to HTMLElements with parents, appending them using appendChild did nothing for the same reason.
I've amended the code below to take care of all of these situations.
Firstly, the code will append a clone of the data to the cell if it's an HTMLElement. I expect in your real code you won't need this, but for this example, why not? It then appends the cell to the row and continues to the next data element.
Secondly, when the data iterator is at 7, before it appends the "Week N" header, it appends a clone of the row, if it has cells on it.
Finally, after appending the clone of the row, the code will reset the row variable to a new instance of a tr element, with no cells.
I also made some variable name and formatting changes to your code just so I could more easily work with it.
function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "6"; // "31"; Why 31? A week has 7 days...
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
/* Major changes start here */
// if the row has cells
if (tre.querySelectorAll('td').length) {
// clone and append to tbody
tbody.appendChild(tre.cloneNode(true));
// reset table row variable
tre = document.createElement('tr');
}
// then append the Week header
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var td = document.createElement('td');
td.classList.add("ui-droppable");
// Set the value of the cell to a clone of the data, if it's an HTMLElement
// Otherwise, make it a text node.
var value = data[j] instanceof HTMLElement ?
data[j].cloneNode(true) :
document.createTextNode(data[j]);
td.appendChild(value);
tre.appendChild(td);
}
// If the number of data elements is not evenly divisible by 7,
// the remainder will be on the row variable, but not appended
// to the tbody, so do that.
if (tre.querySelectorAll('td').length) {
tbody.appendChild(tre.cloneNode(true));
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>

JavaScript - Two tables displayed side by side

Newbie coder here. I am creating an app (see below) that has 2 user input fields located side by side. Parse buttons by these user input fields generate 2 separate tables. The tables are placed vertically and I need them to be placed side by side underneath the user input fields. I've seen many solutions to this problem but they all pertain to html code. I don't know how to do that in JS. Please help! An example of user input would be: 1,2,3,4
realArrayRequest = [];
realArrayResponse = [];
function generateTableRequest(){
var body = document.body;
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for(var i=0; i<msg1Req.length; i++){ //rows
var row=document.createElement("tr");
for (var j=0; j < 3; j++){
if (j === 0){ //columns
var cell = document.createElement("td");
var cellText = document.createTextNode(msg1Req[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 1){
var cell = document.createElement("td");
var cellText = document.createTextNode(realArrayRequest[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 2){
var cell = document.createElement("td");
//cell.setAttribute("contenteditable");
var cellText = document.createTextNode(msg1ReqType[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cell = document.createElement("td");
var cellText = document.createTextNode('');
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function generateTableResponse(){
var body = document.body;
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for(var i=0; i<msg1Res.length; i++){ //rows
var row=document.createElement("tr");
for (var j=0; j < 3; j++){
if (j === 0){ //columns
var cell = document.createElement("td");
var cellText = document.createTextNode(msg1Res[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 1){
var cell = document.createElement("td");
var cellText = document.createTextNode(realArrayResponse[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 2){
var cell = document.createElement("td");
//cell.setAttribute("contenteditable");
var cellText = document.createTextNode(msg1ResType[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cell = document.createElement("td");
var cellText = document.createTextNode('');
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function parseUserInputReq(){
realArrayRequest=[];
//cleans the array from all previous values entered before running all functions
var input = document.getElementById("userInputRequest").value;
var noBracketsStr=input.split(",");
//pushing results from noBracketsStr into a new array realArray, because it seems that split() does not change the original array(string)
for(var i = 0; i < noBracketsStr.length; i++){
realArrayRequest.push(noBracketsStr[i])
}
generateTableRequest();
}
function parseUserInputRes(){
realArrayResponse=[];
//cleans the array from all previous values entered before running all functions
var input = document.getElementById("userInputResponse").value;
var noBracketsStr=input.split(",");
//pushing results from noBracketsStr into a new array realArray, because it seems that split() does not change the original array(string)
for(var i = 0; i < noBracketsStr.length; i++){
realArrayResponse.push(noBracketsStr[i])
}
generateTableResponse();
}
//Message elements
//Message 1
const msg1Req = ['Login Command', 'version', 'xID', 'passcode', 'machineID', 'equipment Serial Number', 'userSlot', 'clubID', 'loginType'];
const msg1ReqType = ['integer', 'integer', 'string', 'string', 'string', 'string', 'integer', 'integer', 'string'];
const msg1Res = ['Login Command', 'Version', 'Result', 'User token'];
const msg1ResType = ['integer', 'integer', 'integer', 'string'];
#parseCommandRequest {
width: 50%;
float: left;
};
#parseCommandResponse {
width: 50%;
float: left;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
<script defer type="text/javascript" src="index.js" charset="UTF-8"></script>
</head>
<body>
<div id="parseCommandRequest">
<form name="userInputReq">
Request
<input type="text" id="userInputRequest">
<input type="button" value="Parse" onclick="parseUserInputReq()">
</form>
</div>
<div id="parseCommandResponse">
<form name="userInputRes">
Response
<input type="text" id="userInputResponse">
<input type="button" value="Parse" onclick="parseUserInputRes()">
</form>
</div>
</body>
</html>
As you mentioned, there's a lot of different ways to solve this. The most common way to solve problems like this is to use CSS. There's actually a quite easy way to achieve this with the CSS you already have. Instead of injecting the two tables in the body you can inject the tables in #parseCommandRequest and #parseCommandResponse. To do this you simply have to replace body.appendChild(tbl); with code to inject them in the correct divs instead.
This is one possible way to achieve that:
// Replace body.appendChild(tbl); with the following
var parseCommandRequestDiv = document.getElementById("parseCommandRequest");
parseCommandRequestDiv.appendChild(tbl);
// Do the same for the response
var parseCommandResponseDiv = document.getElementById("parseCommandResponse");
parseCommandResponseDiv.appendChild(tbl);

Printing JSON in HTML TABLE saved from another table using local storage so that i print my table on another page

In my assignment i have to take the data from user input using and save data in local storage. I have to print this data from local storage in horizontal table format to other pages.For this i made the code for user input and saving data in local storage
<style>
data {
color: #138bc2;
}
</style>
<body>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<div id="POItablediv">
<p>
<input type="button" id="bt" value="Submit Data" onclick="submit()" />
</p>
<input type="button" onclick="insRow()" id="addPOIbutton" value="Add values"/><br/><br/>
<table id="POITable" border="1">
<thead>
<tr>
<td>WEEK NO</td>
<td>Daily exercise</td>
<td>calorie</td>
<td>food</td>
<td>Revision no</td>
<td>Delete?</td>
</tr>
</thead>
<tbody>
<tr>
<td><input size=25 type="text" id="weekbox"/></td>
<td><input size=25 type="text" id="latbox"/></td>
<td><input size=25 type="text" id="lngbox"/></td>
<td><input size=25 type="text" id="lnbox"/></td>
<td><input size=25 type="text" id="lntbox"/></td>
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tbody>
</table>
</body>
<script>
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
if(i>1){
document.getElementById('POITable').deleteRow(i);
}
}
function insRow()
{
var x=document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].childNodes[0].value = "";
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = '';
x.appendChild( new_row );
}
function submit()
{
var table = document.getElementById("POITable")
var tableLen = table.rows.length
var data = {labels: [], alpha: [], beta: [],gamma:[]}
for (var i = 1; i < tableLen; i++)
{
data.labels.push(table.rows[i].cells[0].childNodes[0].value)
data.alpha.push(table.rows[i].cells[1].childNodes[0].value)
data.beta.push(table.rows[i].cells[2].childNodes[0].value)
data.gamma.push(table.rows[i].cells[3].childNodes[0].value)
}
var alphadata = data
localStorage.setItem("quant", JSON.stringify(alphadata));
above code is for taking input from user and saved in local storage .My aim is to print data from local storage to another page in vertical header I mean that the table has the header () tag on the left side (generally).
e<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
</body>
<script>
function CreateTableFromJSON() {
var myBooks =JSON.parse(localStorage.getItem("quant"));
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);
}
</script>
</html>
Table is not printing when i click on button in second page . its gives me blank page . Any lead would be appreciated.
This code implements another function to create a horizontal format.
Please read the comments and also try to understand it so that it can help you in the future
<html>
<body>
<input type="button" onclick="createHorizontal()" value="Create Table From JSON" />
<p id="showData"></p>
<div id="horizontal"></div>
</body>
<script>
function createHorizontal(){
var myBooks = JSON.parse(localStorage.getItem("quant"));
console.log(myBooks);
col_keys = Object.keys(myBooks);
// Object.keys gets the keys of the object
col_values = Object.values(myBooks);
// Object.values gets the values in an object
var final_array = [];
/* Here is the final array that will hold all the data */
for(var i = 0; i < col_keys.length; i++){
var inner = [];
// The inner array that will be pushed with a new value
// after every loop
inner.push("<div class='main'>");
inner.push("<li>" + col_keys[i] + "</li>");
for(var j = 0; j < col_values[0].length; j++){
inner.push("<li>" + col_values[i][j] + "</li>");
}
inner.push("</div>");
//The above code creates the html for each of the rows
inner = inner.join("");
// To remove the commas from the final array
final_array.push(inner);
}
console.log(final_array);
var elem = document.getElementById("horizontal");
var final_div = [];
final_div.push("<div class='container'>");
for(var n = 0; n < final_array.length; n++){
final_div.push(final_array[n]);
}
final_div.push("</div>");
// The above code creates the html for the whole div block
final_div = final_div.join("");
// To remove the commas
console.log(final_div);
elem.innerHTML = "";
elem.innerHTML = final_div;
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
/* Make the rows stack on top of each other */
}
.main {
display: flex;
flex-direction: row;
/* Make the elements in the div stack side by side */
}
.main li {
list-style-type: none;
padding: 5px 10px;
width: 50px;
}
.main li:first-of-type {
font-weight: bold;
background-color: #222222;
color: #ffffff;
}
</style>
</html>
It also uses CSS to make the elements appear in that format or else it would look different. I advise you to analyze and understand it.
So I did not find a problem with the first file that inserts the JSON data to the local storage. The problem was with getting the data from the second file
<html>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
</body>
<script>
function CreateTableFromJSON() {
var myBooks = JSON.parse(localStorage.getItem("quant"));
console.log(myBooks);
/* This logs the object to confirm whether it is there and to
confirm the values inside it You should make this a habit
so that you can check for errors*/
// var col = [];
// for (var i = 0; i < myBooks.length; i++) {
// for (var key in myBooks[i]) {
// if (col.indexOf(key) == -1) {
// col.push(key);
// }
// }
// }
/* The code above is the one I have commented out and replaced with
the one below to get both the keys and values in separate arrays */
col_keys = Object.keys(myBooks);
// Object.keys gets the keys of the object
col_values = Object.values(myBooks);
// Object.values gets the values in an object
// 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.
/* --- REFERENCE 1 --- The length of col_keys and col_values is the same because they
are key and value pairs */
for (var i = 0; i < col_keys.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col_keys[i];
/* col_keys has the keys of the object which are added to
the table header */
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < col_values[0].length; i++) {
/* The loop runs as many times as the number of items in each array
EXPLANATION: col_values contains arrays.
col_values[0].length returns the length of the first array, which is
the array that contains the labels.
And since all the arrays have the same length whether they have a value
or not, the length of the first array is the same for all the others.
--- REFERENCE 2 --- In this case this outer loop runs 2 times*/
tr = table.insertRow(-1);
for (var j = 0; j < col_values.length; j++) {
/* The inner loop runs as many times as the number of key-value pairs
in the object.
EXPLANATION: As " --- REFERENCE 1 --- " above says, this will run **4** times
based on your current object which has:
1.labels
2.alpha
3.beta
4.gamma
*/
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = col_values[j][i];
/* Each time the loop runs, it inserts the "i" value of the array
of each of the values of the object.
Check " --- REFERENCE 2 --- " ... since "i" is less than the length
of each array, it will only run as many times as the number of values
in the array.
In this case **2** times.
*/
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>
There are comments everywhere so make sure to read them and understand why it works that way. Because this is also a learning process. If you have a question just ask.

Add table header for dynamic table in javascript

I'm trying to create a table in javascript and put a header on it. I tried to incorporate the answer from this SO question but perhaps I didn't include it in the right place. The body of the table works perfectly, but the header appends as a bunch of text to the top instead of a nicely formatted header. Here is the code:
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
var header = '<tr><th>Country</th><th>City</th></tr>';
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
tbl.append(header)
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
It prints the rows and the columns correctly, but instead of interpreting the <tr><th> as HTML tags it just prints them out as text. I've also noticed that if the table text contains any HTML tags, like <strong> or <b>, they are returned as plain text as well. How can I make them be read as HTML. I have a CSS page as well but there's no reset or anything (intentionally) affecting the use of bold or tables. Here's my result
<tr><th>Country</th><th>City</th></tr>
1 Row 1 text
2 Row <b>2</b> text
Solution1
The way you are appending tbody rows, you can insert the heading as well. So instead of tbl.append(header) and defining the header string, you can use something like below:
results = {
weak_sent: [
"row 1 data",
"row 2 data"
],
weak_sent_num: [1,2]
}
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
// var header = '<tr><th>Country</th><th>City</th></tr>';
var header= document.createElement('thead')
var headingRow = document.createElement('tr')
var headingCell1 = document.createElement('td')
var headingText1 = document.createTextNode('country')
headingCell1.appendChild(headingText1)
headingRow.appendChild(headingCell1)
var headingCell2 = document.createElement('td')
var headingText2 = document.createTextNode('City')
headingCell2.appendChild(headingText2)
headingRow.appendChild(headingCell2)
header.appendChild(headingRow)
tbl.appendChild(header)
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// This is for the quick solution
// tbl.innerHTML = header
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
generate_table()
Solution2
As a quick solution you can use innerHTML property, as shown below.
results = {
weak_sent: [
"row 1 data",
"row 2 data"
],
weak_sent_num: [1,2]
}
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
var header = '<tr><th>Country</th><th>City</th></tr>';
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// This is for the quick solution
tbl.innerHTML = header
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
generate_table()

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Categories