Create Table Confusion - javascript

I am having some issues / confusion and I am stuck as to where to go from here.
I am experimenting with using Javascript to create tables for my data, and then to display them in HTML. I have created the HTML table without a drama, but the JS one I am having trouble with.
Here is a picture of my expected output:
from here, I have the following code to draw the table. However, I can only get up to the 7th row before I get stuck on how to finish the table.
I have read a lot of references and I can not figure out how to do it!
Here is my code so far:
function drawTable3() {
var input = document.createElement("input");
var tr = document.createElement("tr");
var td = document.createElement("td");
var div = document.getElementById("dropper")
//create table
var drawTable = document.createElement("table");
drawTable.id = "dropperTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("dropperTable");
var input = document.createElement("input");
input.id = "D" + [i] + "Size";
input.type = "number";
//Create Head Elements
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
if ( i == 0) {
createHead.innerHTML = "";
} else if ( i == 1) {
createHead.innerHTML = "Dropper Duct Size";
} else if ( i == 2) {
createHead.innerHTML = "Dropper Duct Capacity";
}
table.appendChild(createHead);
}
for ( var i = 1; i < 7 ; i++ ) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var dropperName = document.createElement("output");
dropperName.id = "D" + [i] + "Size";
dropperName.innerHTML = "Dropper Duct Side " + [i];
cell1.appendChild(dropperName);
var cell2 = row.insertCell(1);
var dropperInput = document.createElement("input");
dropperInput.type = "number";
dropperInput.id = "D" + [i] + "Capacity";
cell2.appendChild(dropperInput);
var cell3 = row.insertCell(2);
var dropperOutput = document.createElement("output");
dropperOutput.id = "D" + [i] + "Capacity";
cell3.appendChild(dropperOutput);
}
}
drawTable3();
.tg {
border-collapse:collapse;
border-spacing:0;
text-align: center;
}
.tg td{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
}
.tg th{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
vertical-align: top;
}
.tg .tg-s6z2{
text-align:center
}
.smallInput {
width: 50px;
text-align: center;
}
.roomIdent {
}
.factors {
text-align: center;
width: 80px;
}
.factors2 {
text-align: center;
width: 150px;
}
.tg2 {
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
border-top-color: #FFF;
border-right-color: #FFF;
border-bottom-color: #FFF;
border-left-color: #FFF;
}
<div id="dropper"></div>

Some comments on your code:
function drawTable3() {
var input = document.createElement("input");
var tr = document.createElement("tr");
var td = document.createElement("td");
tr and td aren't used anywhere, input is re–initialised later.
var div = document.getElementById("dropper")
//create table
var drawTable = document.createElement("table");
drawTable.id = "dropperTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("dropperTable");
You already have a reference to the table as drawTable, so why not call it table from the start? Anyway, the above is equivalent to:
var table = drawTable;
.
var input = document.createElement("input");
You already created an input above and assigned it to input, this replaces it with another input.
input.id = "D" + [i] + "Size";
i hasn't been assigned a value yet (it's declared lower down so it exists as a variable), so its value is undefined. The expression [i] will create the array [undefined] that is then converted to a string because of the + operators and other values in the expression being strings, returning an empty string. So the ID assigned is:
'DSize'
.
input.type = "number";
//Create Head Elements
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
if ( i == 0) {
createHead.innerHTML = "";
} else if ( i == 1) {
createHead.innerHTML = "Dropper Duct Size";
} else if ( i == 2) {
createHead.innerHTML = "Dropper Duct Capacity";
}
table.appendChild(createHead);
}
The above could be a bit more concise if you use an array for the values and assign them based on the value if i. Also, if you are just setting a text value, probably better to insert a text node:
var headCellValues = ['','Dropper Duct Size','Dropper Duct Capacity'];
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
createHead.appendChild(document.createTextNode(headCellValues[i]));
table.appendChild(createHead);
}
.
for ( var i = 1; i < 7 ; i++ ) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
This seems to be the only place that rowCount is used. To append a row using insertRow, provide a value of -1:
var row = table.insertRow(-1);
.
var cell1 = row.insertCell(0);
var dropperName = document.createElement("output");
dropperName.id = "D" + [i] + "Size";
Here again, [1] creates an array that is then converted to a string. Just use i to get say "D0Size":
dropperName.id = "D" + i + "Size";
.
dropperName.innerHTML = "Dropper Duct Side " + [i];
Same here, use:
dropperName.innerHTML = "Dropper Duct Side " + i;
dropperName.appendChild(document.createTextNode("Dropper Duct Side " + i));
The same should be applied to the rest of the code. You might consider cloning entire rows as it's faster than creating all the elements one by one, or making separate functions to create each type of row. It seems that the header and footer parts can be HTML, and only the intervening rows need to be dynamically created.
cell1.appendChild(dropperName);
var cell2 = row.insertCell(1);
var dropperInput = document.createElement("input");
dropperInput.type = "number";
dropperInput.id = "D" + [i] + "Capacity";
cell2.appendChild(dropperInput);
var cell3 = row.insertCell(2);
var dropperOutput = document.createElement("output");
dropperOutput.id = "D" + [i] + "Capacity";
cell3.appendChild(dropperOutput);
}
}
drawTable3();

Related

How can I create a multi-option dynamic dropdown in a table?

I am trying to make a dynamic multi-select option dropdown. The text for the options element in the dropdown are coming from a database that I am fetching. I want each row in the table to have the last column contain this multi-select option dropdown. Right now, the result is it's skipping every row and only on the last row is it displaying all the options multiple times (as amount of times as there are rows). So instead of showing in each row, every row is empty expect the last one and the values are all being showed in the final row. Also, strangely it created empty white space on the right side of the table, like it make new columns. I have attached an image to help visualize this.
How do I display the options properly in each row and how do I make it a multi select dropdown, where if the user clicks one of the options, that option is added to the impact area section.
Thanks.
Image: Image of how it currently looks
Javascript:
//Get Resources and corresponding information and display it in a table
function getResources(){
fetch("______", {
}).then(data => {
var table = document.getElementById("productivity-table");
for(var i=0; i < data.length; i++){
var row = table.insertRow(table.rows.length - 1);
var cell3 = row.insertCell(2);
cell3.classList.add("table-data");
//Cell3 - Create ul and li
var impact_ul = document.createElement("ul");
var impact_li = document.createElement("li");
impact_li.innerHTML = data[i].entity;
impact_li.setAttribute("style", "list-style-type:none");
//Add delete button row
var delete_span = document.createElement("span");
delete_span.className = "delete";
delete_span.innerHTML = "×"
impact_li.appendChild(delete_span);
impact_ul.appendChild(impact_li);
cell3.appendChild(impact_ul);
//Cell5 - Create department dropdown
var dep_dropdown = document.createElement('select');
console.log("dep dropdown", dep_dropdown);
//dep_dropdown.length = 0;
let dep_default = document.createElement('option');
dep_default.text = 'Select Department';
dep_default.disabled = true;
dep_dropdown.add(dep_default);
dep_dropdown.selectedIndex = 0;
fetch("______", {
}).then(data =>{
for(var i=0; i < data.length; i++){
var cell5 = row.insertCell(4);
cell5.classList.add("table-data");
var dep_option = document.createElement('option');
dep_option.text = data[i].dept_name;
dep_option.value = data[i]._id;
dep_dropdown.appendChild(dep_option);
cell5.appendChild(dep_dropdown);
}
}).catch(function(err) {
console.log('Fetch problem: ' + err);
});
}
})
}
here is what you asked for take alook on the snippet
window.onload = function() {
var data = ["option1", "option2", "option3", "option4"];
var table = document.getElementById("productivity-table");
function addslct(dep_dropdown) {
dep_dropdown = document.createElement('select');
dep_dropdown.size = "3";
dep_dropdown.className = "dep_select";
dep_dropdown.id = 'selection';
dep_dropdown.name = 'data options';
dep_dropdown.multiple = "multiple";
dep_dropdown.style.position = "relative";
dep_dropdown.style.width = "100%";
dep_dropdown.style.textAlign = "center";
dep_dropdown.style.color = "darkblue";
return dep_dropdown;
}
function addopts(data) {
var slcts = document.getElementsByClassName('dep_select');
for (var i = 0; i < slcts.length; i++) {
for (var a = 0; a < data.length; a++) {
slcts[i].options.add(optns(data[a], data[a]));
}
}
}
function optns(option, oname) {
var option = document.createElement('option');
option.Value = option;
option.textContent = oname;
return option;
}
table.rows[0].innerHTML += "<th>4</th>";
for (var i = 1; i < table.rows.length; i++) {
var newell = table.rows[i].cells.length;
table.rows[i].insertCell(newell);
table.rows[i].cells[table.rows.length - 1].appendChild(addslct());
}
addopts(data);
document.querySelectorAll('.dep_select').forEach(selectedOptions => {
selectedOptions.addEventListener('click', function() {
var col2 = this.options;
for (var o = 0; o < col2.length; o++) {
var o2 = col2[o];
if (o2.selected == true) {
var rwi = this.parentNode.parentNode.rowIndex;
var cli = this.parentNode.cellIndex;
var cell2 = table.rows[rwi].cells[cli-2];
var slctdopt = o2.value;
if (cell2.innerText.includes(slctdopt) == true) {
var excludez = cell2.innerText.replace("[ "+ slctdopt +" ]", "");
cell2.innerText = excludez + " [ " + slctdopt +" ]";
//cell2.innerText += " [ " + slctdopt +" ]";
} else {
excludez = slctdopt;
cell2.innerText += " [ "+ excludez +" ]";
}
}
}
});
});
}
#productivity-table {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#productivity-table td,
#productivity-table th {
border: 1px solid #ddd;
padding: 8px;
}
#productivity-table td {
text-align: center;
color: blue;
margin: auto;
width:20%;
}
#productivity-table tr:nth-child(even) {
background-color: #f2f2f2;
}
#productivity-table tr:hover {
background-color: #ddd;
}
#productivity-table th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
<table class="table1" id="productivity-table">
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>first</td>
<td></td>
<td>third</td>
</tr>
<tr>
<td>first</td>
<td>[ option2 ]</td>
<td>third</td>
</tr>
<tr>
<td>first</td>
<td>[ option3 ]</td>
<td>third</td>
</tr>
</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.

element switch class but don't get styles of the new class

I'm working on a real-life timetable where you can watch where the students current be. They have six meetings a day. if a student exit the scool i want to delete him from the list. if i doubleclick the name i want to change the class from name to selected and change the backgoundcolor so if i would press the "Schüler löschen"-button all selected get deleted.
Here is the code:
function createTable(){
var table = document.getElementById('table');
for(var j = 0;j<names.length;j++) {
var row = document.createElement("tr");
row.classList.add('row');
for(i=0;i<8;i++){
if(i==0){
var cell = document.createElement("input");
cell.classList.add('name');
cell.value= names[j];
cell.addEventListener("dblclick", function(){
alert(cell.classList);
cell.classList.add('selected');
alert(cell.classList);
});
}else if(i==4){
var cell = document.createElement("td");
cell.classList.add('spacer');
}else{
var cell = document.createElement("td");
cell.classList.add('cell');
cell.textContent = '';
}
row.appendChild(cell);
}
table.children[0].appendChild(row);
}
}
createTable();
the css:
input.name {
width: 20em;
background-color: #00ff00;
}
input.selected{
background-color: #ff7f7f;
}
The problem is if i double click the field the color dosent switch to red it stays green but the alert()-function shows that the class has switched
i've also tried
cell.name {
width: 20em;
background-color: #00ff00;
}
cell.selected{
background-color: #ff7f7f;
}
You need to remove cell class, and use this in that scope.
Try this:
function createTable() {
var table = document.getElementById('table');
var names = ["TEST 1", " TEST 2"];
for (var j = 0; j < names.length; j++) {
var row = document.createElement("tr");
row.classList.add('row');
for (i = 0; i < 8; i++) {
if (i == 0) {
var cell = document.createElement("input");
cell.classList.add('name');
cell.value = names[j];
cell.addEventListener("dblclick", function () {
alert(cell.classList);
this.classList.remove('cell');
this.classList.add('selected');
alert(cell.classList);
});
} else if (i == 4) {
var cell = document.createElement("td");
cell.classList.add('spacer');
} else {
var cell = document.createElement("td");
cell.classList.remove('selected');
cell.classList.add('cell');
cell.textContent = '';
}
row.appendChild(cell);
}
table.children[0].appendChild(row);
}
}
createTable();
input.name {
width: 20em;
background-color: #00ff00;
}
input.selected{
background-color: #ff7f7f;
}
<table id="table"><tbody></tbody></table>
I didn't get why cell is input element and why do you need to added in tr

Recursively creating tables in Javascript

I just started to create something that creates a table with x rows and you can put however many columns in a row that you want. Whenever I attempt to run it, it only creates one cell. How do I fix this?
var xio = parseInt(prompt("How many weighted areas are in this subject?"))
for (i = 5; xio > 0; xio--) {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = "NEW CELL1";
var firstRow = document.getElementById("myTable").rows[xio];
var x = firstRow.insertCell(0);
x.innerHTML = "New cell";
}
<table id="myTable"></table>
There's no prompt for second input so even if the rest of your code was ok (which it isn't) there'd be only one cell. As far as the cells/columns you need to create them in a loop within the loop that creates the rows. Note how the loops syntax is in demo.
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "NEW CELL";
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>
You can simply create table by using the below function
function makeTableHTML(myArray)
{
var result = "<table border=1>";
for(var i=0; i<myArray.length; i++) {
result += "<tr>";
for(var j=0; j<myArray[i].length; j++){
result += "<td>"+myArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
return result;
}
In your code, you are trying to select table.rows[xio] but if xio === 5, the row number 5 doesn't exist yet (because it's iteration 1), so it crashes.
Do it the other way around. Instead of looping by decreasing xio, loop by increasing i.
var xio = parseInt(prompt("How many weighted areas are in this subject?")),
table = document.getElementById("myTable");
for (i = 0; i < xio; i++) {
var row = table.insertRow(0),
cell1 = row.insertCell(0);
cell1.innerHTML = "NEW CELL1";
}
<table id="myTable"></table>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "NEW CELL";
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>

JavaScript onChange Event to use current row values only

An extension of my previous calculators, its now time to look at the onChange or addEventListener functions to run my code without using the submit buttons.
I am having a hard time trying to figure out how I can have the event fire once either the 'H' or 'Extra Room Factor' fields have been changed. I only want the row that is being edited / changed to fire the event, not the entire table. I am trying to figure out how I can 'find' which row / cell is calling the function and then use it in the script to get the other values required.
The script uses JSON to get data which determines how the table is set out.
The code should get the values from L, W and H and multiply them together. It should then multiply the Extra Room Factor and write the result into the 'Total Room M3' field.
(No Rep to post images)
Uh, I have all my code in a fiddle but the current code relies on JSON to get the details. I can't post the fiddle link due to low rep!
jsfiddleFiddle Link
JSON File
Thanks!
function init() {
var url = "http://localhost/javascript/comcool/working/data.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.send(null);
request.onload = function () {
if (request.status === 200) {
result = JSON.parse(request.responseText);
drawMainTable();
drawTable2();
drawTable3();
}
rooms = result.numberOfRooms;
};
}
function drawMainTable() {
var div = document.getElementById("calc");
var drawTable = document.createElement("table");
drawTable.id = "calcTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("calcTable");
//Draw Location Field
for ( var i = 0; i < result.locations.length ; i++ ) {
if ( result.locations[i].name !== null) {
var locations = document.getElementById("location");
var option = document.createElement("option");
option.value = result.locations[i].name;
option.text = result.locations[i].name;
locations.appendChild(option);
}
}
//Create Head Elements
for ( var i = 0; i < result.titles.length; i++ ) {
var createHead = document.createElement("th");
createHead.innerHTML = result.titles[i].name;
table.appendChild(createHead);
}
//Create Row Elements
for ( var i = 0; i < result.numberOfRooms ; i++ ) {
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var roomInput = document.createElement("input");
roomInput.type = "text";
roomInput.id = "R" + i + "Name";
cell1.appendChild(roomInput);
var cell2 = row.insertCell(1);
var lInput = document.createElement("input");
lInput.type = "number";
lInput.id = "R" + i + "L";
lInput.className = "smallInput";
cell2.appendChild(lInput);
var cell3 = row.insertCell(2);
var wInput = document.createElement("input");
wInput.type = "number";
wInput.id = "R" + i + "W";
wInput.className = "smallInput";
cell3.appendChild(wInput);
var cell4 = row.insertCell(3);
var hInput = document.createElement("input");
hInput.type = "number";
hInput.id = "R" + i + "H";
hInput.onchange = calculateRoomM3;
hInput.className = "smallInput";
cell4.appendChild(hInput);
var cell5 = row.insertCell(4);
var extraRoomFactorInput = document.createElement("input");
extraRoomFactorInput.type = "number";
extraRoomFactorInput.id = "R" + i + "Factor";
extraRoomFactorInput.value = "1.0";
extraRoomFactorInput.step = "0.1";
extraRoomFactorInput.min = "1.0";
extraRoomFactorInput.max = "1.3";
cell5.appendChild(extraRoomFactorInput);
var cell6 = row.insertCell(5);
var m3Output = document.createElement("output");
m3Output.id = "R" + i + "M3Total";
cell6.appendChild(m3Output);
var cell7 = row.insertCell(6);
var suggDia = document.createElement("output");
suggDia.id = "R" + i + "Dia";
cell7.appendChild(suggDia);
var cell8 = row.insertCell(7);
var outSize = document.createElement("select");
outSize.id = "R" + i + "OutletSize";
cell8.appendChild(outSize);
for ( var x = 0; x < result.ductInfo.length ; x++ ) {
if ( result.ductInfo[x].ventSize != "nil") {
var option = document.createElement("option");
option.value = result.ductInfo[x].ventSize;
option.text = result.ductInfo[x].ventSize;
outSize.appendChild(option);
}
}
var cell9 = row.insertCell(8);
var ductDia = document.createElement("output");
ductDia.id = "R" + i + "DuctSize";
cell9.appendChild(ductDia);
}
}
function drawTable2() {
var p = document.getElementById("total");
var table = document.createElement("Table");
table.id = "totalTable";
table.className = "tg";
p.appendChild(table);
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++){
var tr = document.createElement('TR');
var outputBox = document.createElement("output");
var inputBox = document.createElement("input");
tableBody.appendChild(tr);
var td = document.createElement('TD');
if ( i === 0 ) {
td.appendChild(document.createTextNode("Total M3 All Rooms:"));
} else if ( i == 1 ) {
td.appendChild(document.createTextNode("Extra House Heat Load:"));
} else if ( i == 2 ) {
td.appendChild(document.createTextNode("Total System m3 Required:"));
}
tr.appendChild(td);
var td = document.createElement('TD');
if ( i === 0 ) {
outputBox.id = "HouseM3Total";
td.appendChild(outputBox);
} else if ( i == 1 ) {
inputBox.type = "number";
inputBox.id = "HouseHeatLoad";
inputBox.value = "1.0";
inputBox.step = "0.1";
inputBox.min = "1.0";
inputBox.max = "1.3";
td.appendChild(inputBox);
} else if ( i == 2 ) {
outputBox.id = "HouseAdjustM3Total";
td.appendChild(outputBox);
}
tr.appendChild(td);
}
}
function drawTable3() {
var div = document.getElementById("dropper");
//create table
var drawTable = document.createElement("table");
drawTable.id = "dropperTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("dropperTable");
//Create Head Elements
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
if ( i === 0) {
createHead.innerHTML = "";
} else if ( i === 1) {
createHead.innerHTML = "Dropper Duct Size";
} else if ( i === 2) {
createHead.innerHTML = "Dropper Duct Capacity";
}
table.appendChild(createHead);
}
for ( var i = 0; i < 6 ; i++ ) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var dropperName = document.createElement("output");
dropperName.innerHTML = "Dropper Duct Side " + [i + 1];
cell1.appendChild(dropperName);
var cell2 = row.insertCell(1);
var dropperInput = document.createElement("input");
dropperInput.type = "number";
dropperInput.id = "D" + [i] + "Size";
cell2.appendChild(dropperInput);
var cell3 = row.insertCell(2);
var dropperOutput = document.createElement("output");
dropperOutput.id = "D" + [i] + "Capacity";
cell3.appendChild(dropperOutput);
}
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var designCapacity = document.createElement("output");
designCapacity.colSpan = "2";
designCapacity.innerHTML = "Design Dropper Capacity";
cell1.colSpan = "2";
cell1.appendChild(designCapacity);
var cell2 = row.insertCell(1);
var DTotalCapacity = document.createElement("output");
DTotalCapacity.id = "DTotalCapacity";
cell2.appendChild(DTotalCapacity);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var modelCapacity = document.createElement("output");
modelCapacity.innerHTML = "Model Dropper Capacity";
cell1.colSpan = "2";
cell1.appendChild(modelCapacity);
var cell2 = row.insertCell(1);
var dropperCapacityUnit = document.createElement("output");
dropperCapacityUnit.id = "dropperCapacityUnit";
cell2.appendChild(dropperCapacityUnit);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var modelSelect = document.createElement("output");
modelSelect.innerHTML = "Model Selection";
cell1.colSpan = "2";
cell1.appendChild(modelSelect);
var cell2 = row.insertCell(1);
var model = document.createElement("output");
model.id = "model";
cell2.appendChild(model);
}
function startCalculate() {
getLocationValue = 0;
totalHouseM3 = 0;
findLocation();
calculateTotalM3();
calculateDuctDia();
findUnitSpecs();
return;
}
function dropperCalculate() {
calculateDropperDia();
finalUnitCalc();
}
function replaceWithDropdownModel( id , valueList ){
var element = document.getElementById( id );
var dropdown = document.createElement("select"),
value = element.value,
option;
dropdown.id = id;
for( var i = 0 ; i < valueList.length ; i++ ){
option = document.createElement("option");
option.text = valueList[i];
option.value = valueList[i];
if( option.value == value){
option.selected = true;
}
dropdown.options.add(option);
}
element.parentNode.replaceChild( dropdown , element );
}
function findLocation() {
var getLocationFactor = document.getElementById("location").value;
for ( var i = 0 ; i < result.locations.length ; i++) {
if (result.locations[i].name === getLocationFactor) {
getLocationValue = result.locations[i].factor;
}
}
}
function calculateTotalM3() {
for ( var i = 0; i < rooms ; i++ ) {
var roomL = document.getElementById("R" + i + "L").value,
roomW = document.getElementById("R" + i + "W").value,
roomH = document.getElementById("R" + i + "H").value,
roomFactor = document.getElementById("R" + i + "Factor").value,
ductDia = document.getElementById("R" + i + "Dia"),
calcM3 = Math.round((roomL * roomW * roomH) * roomFactor);
var outputRoomM3 = document.getElementById("R" + i + "M3Total");
outputRoomM3.innerHTML = calcM3;
totalHouseM3 = totalHouseM3 + calcM3;
var inputHouseHeatLoad = document.getElementById("HouseHeatLoad").value;
var outputHouseM3 = document.getElementById("HouseM3Total");
outputHouseM3.innerHTML = totalHouseM3 + " m3";
for ( var x = 0; x < result.ductInfo.length; x++) {
if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc1 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc1 && getLocationValue === 1) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc2 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc2 && getLocationValue === 2) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc3 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc3 && getLocationValue === 3) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc4 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc4 && getLocationValue === 4) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc5 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc5 && getLocationValue === 5) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
}
}
}
var totalHouseM32 = Math.round(totalHouseM3 * inputHouseHeatLoad);
var outputAdjHouseM3 = document.getElementById("HouseAdjustM3Total");
outputAdjHouseM3.innerHTML = totalHouseM32 + " m3";
}
function calculateDuctDia() {
for ( var i = 0; i < rooms ; i++ ) {
var outletSize = document.getElementById("R" + [i] + "OutletSize").value;
var outputDuctSize = document.getElementById("R" + [i] + "DuctSize");
var diaResult;
for ( var x = 0; x < result.ductInfo.length ; x++) {
if (result.ductInfo[x].ventSize == outletSize) {
diaResult = result.ductInfo[x].ventSize;
}
}
outputDuctSize.innerHTML = diaResult;
}
}
function findUnitSpecs() {
unitArray = [];
for ( var x = 0 ; x < result.modelFinder.length; x++) {
if (totalHouseM3 <= result.modelFinder[x].location1Capacity && getLocationValue === 1) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location2Capacity && getLocationValue === 2) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location3Capacity && getLocationValue === 3) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location4Capacity && getLocationValue === 4) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location5Capacity && getLocationValue === 5) {
unitArray.push(result.modelFinder[x].model);
}
replaceWithDropdownModel( "model" , unitArray);
}
return [
unitArray
];
}
function calculateDropperDia() {
totalDropperCapacity = 0;
dropperSides = 6;
for ( var i = 0; i < dropperSides ; i++ ) {
var dropperSize = document.getElementById("D" + i + "Size").value,
outputDropperCapacity = document.getElementById("D" + i + "Capacity");
var dropperResult;
for ( var x = 0; x < result.ductInfo.length ; x++) {
if (result.ductInfo[x].ductSize == dropperSize) {
dropperResult = result.ductInfo[x].dropperCapacity;
} else if (dropperSize > 551) {
dropperResult = "Size Does Not Exist";
}
}
outputDropperCapacity.innerHTML = dropperResult;
var dropperCapacityElement = document.getElementById("DTotalCapacity");
totalDropperCapacity = totalDropperCapacity + dropperResult;
dropperCapacityElement.innerHTML = totalDropperCapacity;
}
}
function finalUnitCalc() {
var selectedUnit = document.getElementById("model").value,
dropperCapacityUnit = document.getElementById("dropperCapacityUnit");
for ( var i = 0 ; i < result.modelFinder.length ; i++) {
if (selectedUnit === result.modelFinder[i].model) {
dropperCapacityUnit.innerHTML = result.modelFinder[i].dropperCapacity;
}
}
}
window.onload = init;
function calculateRoomM3() {
// iterate through all current rows and get the values of each, save it as a variable in each and then calculate
//
var table = document.getElementById("calcTable");
var rowCount = table.rows[0].cells[1].childNodes[0].value;
console.log(rowCount);
// var roomL =
// roomW =
// roomH =
// roomFactor =
// roomTotal =
// var thisID = document.getElementById(thisID).value,
//thisW = document.getElementById(thisW).value,
//thisL = document.getElementById(thisL).value,
//thisFactor = document.getElementById(thisFactor).value,
//thisTotal = document.getElementById(thisTotal);
//var roomM3 = Math.round((thisL * thisW * thisID)) * thisFactor;
//thisTotal.innerHTML = roomM3;
//console.log(thisID);
//console.log(thisW);
//console.log(thisL);
//console.log(roomM3);
}
#calc{
width: 850px;
margin-bottom: 1em;
}
div {
border: 1px solid white;
}
#dropper {
width: 400px;
position: absolute;
margin-left: 875px;
}
#total {
clear: both;
}
#button2 {
position:absolute;
margin-left: 875px;
margin-top: -250px;
}
h1 {
text-align: center;
}
p {
text-align: center;
}
input {
text-align: center;
}
.tg {
border-collapse:collapse;
border-spacing:0;
text-align: center;
}
.tg td{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
}
.tg th{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
vertical-align: top;
}
.tg .tg-s6z2{
text-align:center
}
.smallInput {
width: 50px;
text-align: center;
}
.factors {
text-align: center;
width: 80px;
}
.factors2 {
text-align: center;
width: 150px;
}
.tg2 {
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
border-top-color: #FFF;
border-right-color: #FFF;
border-bottom-color: #FFF;
border-left-color: #FFF;
}
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="ComCool.js" type="text/javascript"></script>
<meta charset="utf-8">
</head>
<body>
<form>
<div id="dropper">
<h1>Dropper Duct Calculator</h1><br>
<br>
</div>
<div id="calc">
<h1>Calculator</h1>
<p>Location: <select id="location">
</select></p>
</div>
</form>
<div id="total"></div>
<br/>
<div id="button2">
<input onclick="startCalculate()" type="button" value=
"1. Calculate M3, Diameter (Suggested and Actual)">
<br/></br>
<input onclick="dropperCalculate()" type="button" value=
"2. Calculate Dropper"><br>
</div>
<br>
</body>
</html>
I solved this for now by getting the entire ID of the current cell the event runs from, then splicing to get the ID scheme that I have through the table.
var str = this.id,
slice = str.slice(0,2),
roomL = slice + "L",
roomW = slice + "W",
roomH = slice + "H",
roomFactor = slice + "Factor",
roomTotal = slice + "M3Total",
roomDuctDia = slice + "Dia",
Its a quick solve, but it works!

Categories