How to add nested datatable to HTML table - javascript

I am building a table dynamically with JavaScript, and I need to nest another table which will be a jQuery datatable inside the first table which is HTML.
I have what I thought would work and after researching, I don't see why it isn't working. I am defining my first table, building out the header and then adding rows. Inside of a cell, I build the table that will be the datatable.
Using console.log, it looks to be built correctly, but it doesn't display correctly. Instead, it shows only the first table and then appears as if it is not in a table, but rather just haphazardly placed on the page. Here is my code. I would greatly appreciate it if someone will look at it and see if they see a problem with it.
By the way, I don't think it would make any difference, but my openDetailRow function is based on a click coming from a row in an existing datatable.
function openDetailRow() {
$("#gridTbl tr td:nth-child(1)").on("click",
function () {
var ndx = $(this).closest('tr').find('td:eq(0)').text();
var dataRow = reportApp.grid.fnGetData(this.parentNode);
addElements(dataRow);
});
}
function getDetails() {
$("#hdrTbl").dialog({
resizable: false,
modal: true,
title: "Order Details",
height: 250,
width: 700,
buttons: {
"Close": function () {
$(this).dialog('destroy');
$(this).remove();
$("#ordDiv").remove();
}
}
});
}
function buildHdrTable(dataRow){
var hdrDets = [];
hdrDets[0] = dataRow.ordnbr;
hdrDets[1] = dataRow.custordnbr;
hdrDets[2] = dataRow.carrier;
hdrDets[3] = dataRow.custid;
var rowDets = [];
dataRow.detail.forEach(
function (el) {
var rowAr = [];
rowAr[0] = el.invtid;
rowAr[1] = el.descr;
rowAr[2] = el.pcs;
rowAr[3] = el.status;
rowDets.push(rowAr);
});
hdrTbl = document.createElement('table');
hdrTbl.cellPadding = 5;
hdrTbl.style.width = '750px';
hdrTbl.style.display = 'none';
hdrTbl.setAttribute("id", "hdrTbl");
var hdrVals = ["Ord #", "Cust Ord #", "Ship Via", "Cust ID" ];
var tblHead = document.createElement('thead');
hdrTbl.appendChild(tblHead);
tblHeadRow = document.createElement("tr");
tblHead.appendChild(tblHeadRow);
for(var i =0; i < hdrVals.length; i++){
tblHeadRow.appendChild(document.createElement("th")).
appendChild(document.createTextNode(hdrVals[i]));
}
var hdrBody = document.createElement("tbody");
hdrTbl.appendChild(hdrBody);
var tr = hdrBody.insertRow();
var td1 = tr.insertCell();
var td2 = tr.insertCell();
var td3 = tr.insertCell();
var td4 = tr.insertCell();
td1.appendChild(document.createTextNode(hdrDets[0]));
td2.appendChild(document.createTextNode(hdrDets[1]));
td3.appendChild(document.createTextNode(hdrDets[2]));
td4.appendChild(document.createTextNode(hdrDets[3]));
var bdy = hdrBody.insertRow();
var bdyTbl = bdy.insertCell();
tbl = document.createElement('table');
tbl.style.width = '100%';
tbl.style.display = 'none';
//tbl.style.border = "1px solid black";
tbl.setAttribute("id", "ordertable");
var headVals = ["Inventory Number", "Description", "Number of Pieces", "Status"];
var thead = document.createElement('thead');
tbl.appendChild(thead);
var theadRow = document.createElement("tr");
thead.appendChild(theadRow);
for (var i = 0; i < headVals.length; i++) {
theadRow.appendChild(document.createElement("th"))
.appendChild(document.createTextNode(headVals[i]));
}
var tbody = document.createElement("tbody");
tbl.appendChild(tbody);
for (var i = 0; i < rowDets.length; i++) {
var tr = tbody.insertRow();
var td1 = tr.insertCell();
var td2 = tr.insertCell();
var td3 = tr.insertCell();
var td4 = tr.insertCell();
td1.appendChild(document.createTextNode(rowDets[i][0]));
td2.appendChild(document.createTextNode(rowDets[i][1]));
td3.appendChild(document.createTextNode(rowDets[i][2]));
td4.appendChild(document.createTextNode(rowDets[i][3]));
bdyTbl.appendChild(tbl);
}
return hdrTbl;
}
function addElements(dataRow) {
var body = document.body;
var hdrTbl = buildHdrTable(dataRow);
ordDiv = document.createElement("div");
ordDiv.appendChild(hdrTbl);
ordDiv.setAttribute("id", "ordDiv");
body.appendChild(ordDiv);
$("#ordertable").css('display', 'none');
$("#ordertable").dataTable(tbl);
getDetails();
console.log(hdrTbl);
}

The issue was caused because I was using display:none. Now here is the thing.. If you don't use that particular style attribute, then the table will show up on the page. However, since it is nested inside my first table, and the first table has the display:none style attribute already applied to it, then by applying it to the second table, it would not allow that table to be shown on page.
As for the skewed look, I had not set a colspan. So now, it is working perfectly. I commented out the display none and added this one line of code...
bdyTbl.setAttribute("colspan", 4);

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>

How can I make a tableRow tappable? I've watched online but it didn't work

I would like to open a new page when I tap a cell (TR) in Javascript. I've searched a lot of tutorials online but it doesn't work as well. I hope that someone could help me. Thanks.
Here is my code:
function generateTableBirre()
{
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("Table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
row = table.insertRow(-1);
var cell = row.insertCell(-1);
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
cell.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
If you would like to show the table, here is the image:
In the Javascript below the table is created with 2 cells per row. In the first cell you'll find a div with a text paragraph. In the second cell you'll find a div with anchor and image.
Important: an id must be unique so I had to remove lines where duplicate id's were created. If you want to use extra selectors then you can use classList.add("...")
In the css you can style the image width, font, color, etc. For example #dvTable img { max-width: 250px; height: auto; border: 0; }
function generateTableBirre() {
// array containing records
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
// create table
var table = document.createElement('table');
table.classList.add("Birre");
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '20');
// loop through the array and create rows
for (var i = 0; i < birre.length; i++) {
var row = document.createElement('tr');
// loop from 0 to 1 to create two cells on each row
for (var j = 0; j < 2; j++) {
var cell = document.createElement('td');
// give each cell a inner div
var div = document.createElement("div");
div.classList.add("General-Div");
cell.appendChild(div);
// different content in cell 0 and cell 1
if (j == 0) {
// cell 0 contains paragraph
var par = document.createElement("p");
par.innerHTML = birre[i] + ' - ' + price[i];
div.appendChild(par);
} else {
// cell 1 contains image in an anchor
var anch = document.createElement('a');
anch.setAttribute('href', 'Antipasti.html');
div.appendChild(anch);
var img = document.createElement("img");
img.setAttribute('src', 'https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png');
anch.appendChild(img);
}
row.appendChild(cell);
}
table.appendChild(row);
}
// append table in id=dvTable
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
generateTableBirre();
<div id="dvTable">
</div>
try this,
function generateTableBirre() {
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
//var row = table.insertRow(-1);
//var cell = row.insertCell(-1);
var row = document.createElement("tr");
table.appendChild(row);
var cell = document.createElement("td");
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
row.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}

How do I search a table that is created with javascript

I have a table that is created by javascript when it obtains data from the data base, this is the function
function gotCData(snapshot){
snapshot.forEach(userSnapshot => {
var confirmed = userSnapshot.val().confirmed;
var date = userSnapshot.val().date;
var deaths = userSnapshot.val().deaths;
var recovered = userSnapshot.val().recovered;
//console.log(confirmed, date, deaths, recovered);
var local = k;
var csvDate = date;
var population = recovered;
var totalCases = confirmed;
var totalDeaths = deaths;
//console.log(location);
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var td5 = document.createElement('td');
var tdLocal = document.createTextNode(local);
var tdPopulation = document.createTextNode(population);
var tdTotalCases = document.createTextNode(totalCases);
var tdTotalDeaths = document.createTextNode(totalDeaths);
var tdDate = document.createTextNode(csvDate);
td1.appendChild(tdLocal)
td2.appendChild(tdPopulation)
td3.appendChild(tdTotalCases)
td4.appendChild(tdTotalDeaths)
td5.appendChild(tdDate)
var tRow1 = document.getElementById("displayCorona").appendChild(td1);
var tRow2 = document.getElementById("displayCorona").appendChild(td2);
var tRow3 = document.getElementById("displayCorona").appendChild(td3);
var tRow4 = document.getElementById("displayCorona").appendChild(td4);
var tRow5 = document.getElementById("displayCorona").appendChild(td5);
//Writes the Table Row then the Divs after
document.getElementById("displayCorona").appendChild(tr, tRow1, tRow2, tRow3, tRow4, tRow5);
});
}
I have a search function :
function search(){
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("displayCorona");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td1")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
The tables are created when I loop through each node in a Firebase database. The search function is from W3Schools but im not sure why it is not searching the table that is created by the above function.
Here's some code for you to look at.
"use strict";
function newEl(tag){return document.createElement(tag)}
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoad, false);
function onLoad(evt)
{
var inputStr = "I have a table that is created by javascript when it obtains data from the data base, this is the function";
document.body.appendChild( makeTable(inputStr) );
byId('goBtn').addEventListener('click', onGoBtn, false);
}
function makeTable(input)
{
let tbl = newEl('table');
input = input.replace(',', '');
let words = input.split(' ');
let nWords = words.length;
let nRows = parseInt(nWords/5) + nWords%5;
for (var j=0; j<nRows; j++)
{
let tr = newEl('tr');
for (var col=0; col<5; col++)
{
let td = newEl('td');
td.textContent = words[j*5 + col];
tr.appendChild(td);
}
tbl.appendChild(tr);
}
return tbl;
}
function highlightContainingCells(input, highlightClassname)
{
let cells = document.querySelectorAll('td');
cells.forEach( cellFunc );
function cellFunc(curCell)
{
if (input == curCell.textContent)
curCell.classList.add(highlightClassname);
else
curCell.classList.remove(highlightClassname);
}
}
function onGoBtn(evt)
{
let str = byId('searchStr').value;
highlightContainingCells(str, "found");
}
td
{
color: #333;
background-color: #ddd;
}
td.found
{
color: #ddd;
background-color: #333;
}
<input id='searchStr' value='javascript'/><button id='goBtn'>SEARCH</button></br>
There were so many wrong things.
You had not specified what data type snapshot is. Is it array or something else? I assumed it to be array of JSON objects, where each object denotes a row in your table.
I did not understand the use of .val() method. I removed it completely.
The table being generates was not in correct format. You were appending tr to table. But instead of appending td to tr you were also appending them to table. I have corrected that also.
There was an undefined variable k which was being used to set local.
display:block style on tr was displaying table in a weird way once rows are eliminated. I changed it to display:table-row instead, which is ideal for table-rows
function gotCData(snapshot) {
snapshot.forEach(userSnapshot => {
var confirmed = userSnapshot.val().confirmed;
var date = userSnapshot.val().date;
var deaths = userSnapshot.val().deaths;
var recovered = userSnapshot.val().recovered;
var local = userSnapshot.local; // we will look at this later
// console.log(confirmed, date, deaths, recovered);
// var local = k;
var csvDate = date;
var population = recovered;
var totalCases = confirmed;
var totalDeaths = deaths;
//console.log(location);
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var td5 = document.createElement('td');
var tdLocal = document.createTextNode(local);
var tdPopulation = document.createTextNode(population);
var tdTotalCases = document.createTextNode(totalCases);
var tdTotalDeaths = document.createTextNode(totalDeaths);
var tdDate = document.createTextNode(csvDate);
td1.appendChild(tdLocal)
td2.appendChild(tdPopulation)
td3.appendChild(tdTotalCases)
td4.appendChild(tdTotalDeaths)
td5.appendChild(tdDate)
tr.appendChild(td1)
tr.appendChild(td2)
tr.appendChild(td3)
tr.appendChild(td4)
tr.appendChild(td5)
// Writes the Table Row then the Divs after
document.getElementById("displayCorona").appendChild(tr);
});
}
function search() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("displayCorona");
tr = table.querySelectorAll("tr:not(.table-head)");
// Loop through all table rows, and hide those who don't match the search query
var found
for (i = 0; i < tr.length; i++) {
tds = tr[i].getElementsByTagName("td")
if (tds) {
found = false
for (j = 0; j < tds.length && found == false; j++) {
td = tds[j];
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "table-row";
found = true
break
}
}
if (found == false) tr[i].style.display = "none";
}
}
}
// This is used for testing only
// window.onload = () => {
// snapshot = firebaseToArray(firebaseJSON)
// gotCData(snapshot)
// }
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="myInput">
<button type="submit" onclick="search()">Search</button>
<table id="displayCorona">
<tr class="table-head">
<th>Location</th>
<th>Population</th>
<th>Total cases</th>
<th>Total deaths</th>
<th>Date</th>
</tr>
</table>
</body>
</html>
Some friendly advice:
I see you have extracted data from snapshot and assign them twice to variables, for say you first extract date from snapshot and then assign it to csvDate, while you could directly extract date to csvDate
You were creating text nodes for td, assigning them values and appending them to corresponding td node. You could directly insert data using innerHTML or innerText for example, td1.innerText = local. No need to create textNodes and append them!
It seems like you directly copy-pasted code for search function from w3schools. Please review such codes after using.
Use developer console to find common errors. Debugging your code can solves many common problems, so get familiar with it.

Tables not coming in center of div

I am trying to create 3 tables by Javascript inside a div and then put them inside HTML of an existing div. Please find the entire code here:
https://jsfiddle.net/s78n3dfe/
HTML File
<div id = "tldr">
</div>
Javascript File
map1 = [["label1", 30], ["label2", 70]];
total1 = 100;
title1 = "dasdas";
var table1 = createTable(map1, total1, title1);
var table2 = createTable(map1, total1, title1);
var table3 = createTable(map1, total1, title1);
var divNode = document.createElement('div');
divNode.setAttribute("id", "labelInfo");
divNode.appendChild(table1);
divNode.appendChild(table3);
divNode.appendChild(table2);
var tldr = document.getElementById('tldr');
tldr.appendChild(divNode);
function createTable(map, total, title) {
var table = document.createElement('table');
table.setAttribute("class", "table");
table.classList.add("table-striped");
// table.setAttribute("class", "table-striped");
table.setAttribute("style", "display: inline-block; width:33%;");
var caption = table.createCaption();
caption.setAttribute("style", "text-align: center;")
caption.innerHTML = title.toString().bold();
var header = table.createTHead();
var firstRow = header.insertRow(0);
var header1 = firstRow.insertCell(0);
var header2 = firstRow.insertCell(1);
header1.innerHTML = "Label".bold();
header2.innerHTML = "Allocation".bold();
var tblBody1 = document.createElement("tbody");
tblBody1.setAttribute('class', 'percentageBody');
tblBody1.setAttribute('style', 'display:block; border-top: 0px;');
table.appendChild(tblBody1);
for(label in map) {
var row = document.createElement("tr");
var labelCell = row.insertCell(0);
var percentCell = row.insertCell(1);
labelCell.innerHTML = map[label][0].bold();
percentCell.innerHTML = map[label][1].toString().concat(" %");
tblBody1.appendChild(row);
}
var tblBody2 = document.createElement("tbody");
tblBody2.setAttribute('class', 'valueBody');
tblBody2.setAttribute('style', 'display:none; border-top: 0px;');
table.appendChild(tblBody2);
for(label in map) {
var row = document.createElement("tr");
var labelCell = row.insertCell(0);
var percentCell = row.insertCell(1);
labelCell.innerHTML = (map[label][0]).bold();
percentCell.innerHTML = (map[label][1]/100 * total).toFixed(0).toString();
tblBody2.appendChild(row);
}
return table;
}
The problem I am facing is that tables are coming towards the left side of the div and not coming in the center. How can I make them come in the center?
Please check below Code:
Remove Inline-block from table's CSS:

Delete row from table dynamically created in javaScript

I want to delete a row from a table created by JavaScript. i tried the code from different post on this page but doesn't solve it.
function value_pass()
{
var Delete = document.createElement("input");
Delete.type="button";
Delete.name = "del"
Delete.value = "Delete";
Delete.onclick = function(o)
{
var r = o.parentElement.parentElement;
document.getElementById("table").deleteRow(r.rowIndex);
}
var order_no = document.getElementById("Order_no");
var quantity = document.getElementById("quantity");
var type = document.getElementById("Recipe");
var recipe = type.options[type.selectedIndex].text;
var body1 = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute("id","table");
var tblbody = document.createElement("tbody");
tbl.setAttribute("border","2");
var col = document.createElement("td");
for (var j = 0; j < 1; j++)
{
var rows = document.createElement("tr");
for (var i = 0; i < 4; i++)
{
var col1 = document.createElement("td");
var col2 = document.createElement("td");
var col3 = document.createElement("td");
var col4 = document.createElement("td");
var col5 = document.createElement("td");
var col1text = document.createTextNode(order_no.value);
var col2text = document.createTextNode(recipe);
var col3text = document.createTextNode(quantity.value);
var col4text = document.createTextNode();
//also want to put checked values in table row
}
col1.setAttribute("width","150");
col2.setAttribute("width","150");
col3.setAttribute("width","150");
col4.setAttribute("width","150");
col1.appendChild(col1text);
col2.appendChild(col2text);
col3.appendChild(col3text);
col4.appendChild(col4text);
col5.appendChild(Delete);
rows.appendChild(col1);
rows.appendChild(col2);
rows.appendChild(col3);
rows.appendChild(col4);
rows.appendChild(col5);
tblbody.appendChild(rows);
} tbl.appendChild(tblbody);
body1.appendChild(tbl);
}
The function will be called by a button in HTML
its an order form that
and also want to know about the checked values of checkbox to put in the table row.
You can use :
document.getElementById("myTable").deleteRow(0); //Where 0 is your row.
Explained : http://www.w3schools.com/jsref/met_table_deleterow.asp
Edit:
To delete the current row, set this on your button: onclick="deleteRow(this), with the following code in that function:
function deleteRow(t)
{
var row = t.parentNode.parentNode;
document.getElementById("myTable").deleteRow(row.rowIndex);
console.log(row);
}

Categories