How do I search a table that is created with javascript - 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.

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>

Set input to read only?

I am trying to build a grade book web app. I wanted to be able to edit the table cells to input grades, but I can't set it to readonly. What am I doing wrong?
I tried changing the code in the save button, but nothing works. I cant seem to get the input tags for some reason.Am I missing something? Is there another way to try to set the cells to readOnly? I tried getting the td tags, but that didn't work.
var myTable = document.getElementById("myTable");
var r = 0;
var c = 1;
function addRow() {
//insert a row
var row = myTable.insertRow(r);
//insert cells into a row
var cell = row.insertCell(0);
cell.innerHTML = "Students[i]";
r++;
}
function addColumn() {
//add new cell to each row
var allRows = document.getElementsByTagName("tr");
for (var i = 0; i < allRows.length; i++) {
row2 = allRows[i];
cell2 = allRows[i].insertCell(c);
cell2.innerHTML = "Puff";
}
}
function editCell() {
var allCells = document.getElementsByTagName("td");
for (var j = 0; j < allCells.length; j++) {
//clear text, then put in input box
allCells[j].innerHTML = "";
var myInput = document.createElement("input");
myInput.type = "text";
myInput.readOnly = false;
allCells[j].appendChild(myInput);
}
}
function saveData() {
//turn all inputs into readOnly
var allInputs = document.getElementsByTagName("td");
for (var k = 0; k < allInputs.length; k++) {
allInputs[k].id = "inpoot";
document.getElementById("inpoot").readOnly = true;
}
//document.getElementsByTagName("input").readOnly = true;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<table id="myTable"></table>
<button onClick="addRow()">Students</button>
<button onClick="addColumn()">Days</button>
<button onClick="editCell()">Edit</button>
<button onClick="savaData()">Save</button>
HTML IDs must be globally unique within a document. Since you're setting the ID to inpoot for each one, then the getElementById call is always going to be selecting the same element. Also, these elements are the tds, not the inputs themselves.
Try changing your save function thusly:
function saveData(){
//turn all inputs into readOnly
document.querySelectorAll("td > input").forEach(input => {
input.readOnly = true;
});
}
Is there another way to try to set the cells to readOnly?
Use this :
JS :
var myInput = document.createElement("input");
myInput.classList.add("readOnly-input");
CSS :
.readOnly-input{ pointer-events: none; }
The user can't interact when pointer-events are set to none. Let me know if you need more explaination.

Forbid row insertion | no jQuery

I have a dynamic table. Data comes from inputs by Create button click.
If at least one row includes current input ID-field value (not inserted yet) program should forbid row insertion.
I tried to add checkId() logic but it didn't work for me:
checkId = () => {
var isDuplicate = false;
var idVal = inputs[0].value;
if (textbox.value.includes(idVal)){
isDuplicate = true;
row.remove();
alert("Pease, enter unique ID")
}
return isDuplicate;
}
Is there any way to implement this logic within existing code (no jQuery)?
Here are both html and js:
let headerArr = new Array();
headerArr = ['ID', 'Fname', 'Lname', 'Age'];
//console.log(headerArr.length)
//inputs
var div = document.getElementById('enter');
var inputs = div.getElementsByTagName('input')
var count = 0;
createTable = () => {
let storage = document.createElement('table');
storage.setAttribute('id', 'storage'); //set the table ID
let row = storage.insertRow(-1);
for (let h = 0; h < headerArr.length; h++) { //table header
let headCols = document.createElement('th');
headCols.innerHTML = headerArr[h];
row.appendChild(headCols);
}
let div = document.getElementById('dynamicTable');
div.appendChild(storage); //add the table to the page
}
/* checkId = () => {
var isDuplicate = false;
var idVal = inputs[0].value;
//textbox = document.createElement('input')
if (textbox.value.includes(idVal)){
isDuplicate = true;
row.remove();
alert("Pease, enter unique ID")
}
return isDuplicate;
} */
//add a new row to the table
addEnd = () => {
let table = document.getElementById('storage');
var rowCount = table.rows.length; //get table row count
var row = table.insertRow(rowCount)
var textbox;
// if((!checkId()) && rowCount > 1){
for (let c = 0; c <= headerArr.length - 1; c++) {
var cell = document.createElement('td');
cell = row.insertCell(c);
textbox = document.createElement('input');
textbox.setAttribute('type', 'text');
textbox.setAttribute('readonly', true);
textbox.setAttribute('value', inputs[c].value);
cell.appendChild(textbox);
}
// }
}
let createBtn = document.getElementById('create-btn');
createBtn.addEventListener('click', addEnd, false);
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
<style>
table {
width: 100px;
border-spacing: 10px;
padding: 10px;
}
table,
th,
td {
border: 1px solid gray;
border-collapse: collapse;
padding: 2px 3px;
text-align: left;
}
.enter {
display: block;
float: right;
margin-bottom: 10px
}
}
</style>
</head>
<body onload="createTable()">
<div id="dynamicTable"></div>
<div id="enter" class="enter">
<p>ID:<br>
<input class="enter__id" type="text" id="id"></input>
<br>
<p>First name:<br>
<input class="enter__name type=" text " id="name "></input>
<br>
<p>Last name:<br>
<input class="enter__surname type="text" id="surname"></input>
<br>
<p>Age:<br>
<input class="enter__age" type="text" id="age"></input>
<br>
<button id="create-btn">Create</button>
<button id="update-btn">Update</button>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Please, help me to find the right way to solve it.
if (textbox.value.includes(idVal))
Your condition isn't valid, because you try to get .value from a variable that is undefined in your context.
I fix your js code :
let headerArr = new Array();
headerArr = ['ID', 'Fname', 'Lname', 'Age'];
//console.log(headerArr.length)
//inputs
var div = document.getElementById('enter');
var inputs = div.getElementsByTagName('input')
var count = 0;
createTable = () => {
let storage = document.createElement('table');
storage.setAttribute('id', 'storage'); //set the table ID
let row = storage.insertRow(-1);
for (let h = 0; h < headerArr.length; h++) { //table header
let headCols = document.createElement('th');
headCols.innerHTML = headerArr[h];
row.appendChild(headCols);
}
let div = document.getElementById('dynamicTable');
div.appendChild(storage); //add the table to the page
}
checkId = () => {
var idVal = inputs[0].value;
for (var i = 0; i < document.getElementsByClassName('id_cells').length; i++) {
let el_id = document.getElementsByClassName('id_cells');
if (el_id.value = idVal) {
alert("Pease, enter unique ID");
return true
}
}
return false;
}
//add a new row to the table
addEnd = () => {
let table = document.getElementById('storage');
var rowCount = table.rows.length; //get table row count
var row = table.insertRow(rowCount)
if ((!checkId()) && rowCount > 1) {
for (let c = 0; c <= headerArr.length - 1; c++) {
var cell = document.createElement('td');
cell = row.insertCell(c);
textbox = document.createElement('input');
textbox.setAttribute('type', 'text');
textbox.setAttribute('readonly', true);
textbox.setAttribute('value', inputs[c].value);
if (c == 0) {
textbox.setAttribute('class', 'id_cells');
}
cell.appendChild(textbox);
}
}
}
let createBtn = document.getElementById('create-btn');
createBtn.addEventListener('click', addEnd, false);
When you create your cells, if it's the first of the row (where the id should be displayed), I add a class to the cell to keep a reference. When you need to check for duplicate id, you get all the tag with the class i set beforehand and check their id in a loop.
I hope it solved your issue

How to pass var values to a parameter in javascript?

I was trying to use 2 different tables, different input field, and different text in a single script. I use this script below to pass those values on a function parameter to get those values. The problem is I am not getting the input.value but I can get the input1.value. I think the input1 is not going inside the filterFunction(input) above
<script type="text/javascript">
function filterFunction(table, input, total_amount_id) {
var filter, tr, td, i, totalViewable = 0;
console.log(input1.value);
console.log(input);
filter = input.value.toUpperCase();
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
tds = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
totalViewable += parseFloat(tds.innerHTML);
document.getElementById(total_amount_id).innerHTML = "$" + totalViewable.toFixed(2);
} else {
tr[i].style.display = "none";
}
}
}
}
var table1 = document.getElementById("dateTable");
var input1 = document.getElementById("event_date_range");
var total_amount_id1 = "total_amount_td";
filterFunction(table1, input1, total_amount_id1);
var table2 = document.getElementById("dateTable2");
var input2 = document.getElementById("event_date_range2");
var total_amount_id2 = "total_amount_td2";
filterFunction(table2, input2, total_amount_id2);
</script>
var input1 = document.getElementById("event_date_range");
In this expression you are placing value in input1.
so you cannot ge the {input} value.

How to add nested datatable to HTML table

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

Categories