Creating a table with a loop - javascript

I'm quite new to Javascript and I'm trying to populate a table through a loop. The code works fine as long as I only try to populate the table, but when I try to add an IF condition in order to separate headers and data, it does not work any more. I would be curious to understand why it does not work and how can I solve the issue.
Below current broken code:
for(i = 0;i < values.length; i ++){
var table = document.getElementById("myTable");
tr = document.createElement('tr');
for (j = 0; j < values[i].length; j++) {
if (i=0) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
} else {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
}
Here the code that works without headers:
for(i = 0;i < values.length; i ++){
var table = document.getElementById("myTable");
tr = document.createElement('tr');
for (j = 0; j < values[i].length; j++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
table.appendChild(tr);
}

you should put double equal i==0 not i=0
if (i==0) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
EDIT
in your second loup you should close the if statement and loop :
for (i = 0; i < values.length; i++) {
var table = document.getElementById("myTable");
tr = document.createElement('tr');
for (j = 0; j < values[i].length; j++) {
if (i == 0) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
} else {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
}
}

Related

Javascript : Creating a dynamic table with column title on the first row and row title in the first column

I am trying to create a table with title to be displayed on the first and second row and first column. The first row will have the same name which is working fine. But with my below script the row title (starting from 3rd row) displays in the last column than the first.
Please advise where am I going wrong with this.
var body = document.getElementsByTagName("body")[0];
var yardName = "B1";
var colsInYard = 5;
var rowsInYard = 5;
var tbl = document.createElement("table");
tbl.setAttribute("id", "our_table");
var tblHead = document.createElement("thead");
for (var r = 0; r < 1; r++) {
// creates a table row
var row = document.createElement("tr");
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c != 0) {
var cellText = document.createTextNode(yardName);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblHead.appendChild(row);
}
for (var r = 0; r < 1; r++) {
var row = document.createElement("tr");
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c != 0) {
var cellText = document.createTextNode(c);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblHead.appendChild(row);
}
tbl.appendChild(tblHead);
var tblBody = document.createElement("tbody");
for (var r = 1; r <= rowsInYard; r++) {
var row = document.createElement("tr");
var cellText = document.createTextNode(r);
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "0");
tbl.setAttribute("cellpadding", "0");
tbl.setAttribute("cellspacing", "0");
My fiddle https://jsfiddle.net/udopgxLv/1/
I believe you just need to add an IF statement to the code in the tbody section to get the data to post into the first column. I modified your jfiddle with the code below (just 2 lines added) and the values are inserted properly.
for (var r = 1; r <= rowsInYard; r++) {
var row = document.createElement("tr");
var cellText = document.createTextNode(r);
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c==1){ // <--- this was added
cell.appendChild(cellText);
} // <--- this was also added
row.appendChild(cell);
}
tblBody.appendChild(row);
}
You missed if statement in create tbody
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c=== 0)
cell.appendChild(cellText);
row.appendChild(cell);
}
https://jsfiddle.net/udopgxLv/3/

How to remove an entire table using javascript?

I have a calendar table, that shows the entire month's date, if user chose to see next month or previous I need to delete the entire table and replace the new table in that same place, at the moment each table is loading underneath the other because I cant get this to work.
I need to remove table from calendar-dates. but I had no luck. I have used removechild("tb") but didnt work, I also tried var test = document.getElementById("calendarDates");
test.removeChild(test.childNodes[0]);
Here is the code for the table:
document.getElementById("calendar-dates").appendChild(calendar);
Table:
//add calendar table
function get_calendar(day_no, days, m , y){
var table = document.createElement('table');
table.id = "tb";
var tr = document.createElement('tr');
//row for the day letters
for(var c=0; c<=6; c++){
var td = document.createElement('td');
td.innerHTML = "SMTWTFS"[c];
tr.appendChild(td);
}
table.appendChild(tr);
//create 2nd row
tr = document.createElement('tr');
var c;
for(c=0; c<=6; c++){
if(c == day_no){
break;
}
var td = document.createElement('td');
td.innerHTML = "";
tr.appendChild(td);
}
var count = 1;
for(; c<=6; c++){
var td = document.createElement('td');
td.innerHTML = count;
td.style.cursor = "pointer";
td.id = count;
td.onclick = function () {
m = m + 1;
document.getElementById("cDD").value = this.id + "/" + m + "/" + y;
document.getElementById("calendar-container").style.display = "none";
};
count++;
tr.appendChild(td);
}
table.appendChild(tr);
//rest of the date rows
for(var r=3; r<=7; r++){
tr = document.createElement('tr');
for(var c=0; c<=6; c++){
if(count > days){
table.appendChild(tr);
return table;
}
var td = document.createElement('td');
td.innerHTML = count;
td.style.cursor = "pointer";
td.id = count;
td.onclick = function () {
m = m + 1;
document.getElementById("cDD").value = this.id + "/" + m + "/" + y;
document.getElementById("calendar-container").style.display = "none";
};
count++;
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
The removeChild method takes a node, not an ID.
test.removeChild(test.childNodes[0]); probably doesn't work because you have some text nodes before the table.
test.removeChild(test.firstElementChild)probably will work
document.getElementById("calendar-dates").removeChild(document.getElementById('tb'))
document.querySelector('button').addEventListener('click', () => {
document.getElementById('wrapper').removeChild(document.querySelector('table'));
})
table, th, td {
border: 1px solid red;
padding: 2px
}
<div id="wrapper">
<table>
<tr>
<td>Table</td>
<td>Content</td>
</tr>
</table>
</div>
<button>Remove table</button>
Does #calendar-dates contains other html than tables? If not, you can set innerHtml to empty
var calendarDates = document.getElementById("calendar-dates");
calendarDates.innerHtml = '';
calendarDates.appendChild(calendar);

Create table column-headers dynamically

Right now I cannot figure out how to add headers for all the columns in this code where a html-table are created dynamically
function createTableAndInsert(sqlArray) {
//create table dynamically - only one row by the moment
var table = document.createElement('table');
for (var i = 1; i < 2; i++) {
var tr = document.createElement('tr'); // row
for (var j = 0; j < 8; j++) {
var td = document.createElement('td'); //column
var text = document.createTextNode(sqlArray[j]); //cell
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);
}
You can pass the header list separately to your function and add following code
function createTableAndInsert(sqlArray,headerList) {
var table = document.createElement('table');
var tr = document.createElement('tr'); // Header row
for (var j = 0; j < 8; j++) {
var th = document.createElement('th'); //column
var text = document.createTextNode(headerList[j]); //cell
th.appendChild(text);
tr.appendChild(th);
}
table.appendChild(tr);
for (var i = 1; i < 2; i++) {
var tr = document.createElement('tr'); // row
for (var j = 0; j < 8; j++) {
var td = document.createElement('td'); //column
var text = document.createTextNode(sqlArray[j]); //cell
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);
}
Your structure is:
<tr>
<td>
<div></div>
<div></div>
</td>
</tr>
thead should be appended before each row.
<thead></thead>
<tr>
<td>
<div></div>
<div></div>
</td>
</tr>
Solution:
var thead = document.createElement('thead');
thead.innerHTML = 'Header';
Before table.appendChild(tr);, add this line table.appendChild(thead);
THEAD needs one or more TR elements:
var table = document.createElement('table'); // 'table' may be a reserved word
var tblHead = document.createElement('thead');
var rowHead = document.createElement('tr');
table.appendChild(tblHead);
tblHead.appendChild(rowHead)
for(j=0; j<8; j++) {
var celHead = document.createElement('th');
//the array txtHeaders[] should be passed to your function if you have the values in advance
// otherwise, you can access the header cells later by:
// table.getElementsbyTagName('th')[].innerHTML
celHead.innerHTML = txtHeaders[j]
rowHead.appendChild(celHead)
}
// now do your row & table loops

Dynamically generated table - using an array to fill in TD values

I need your help,
For some reason, I can't get the data captured in my array to populate into the TD cells of my dynamically generated table:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "Request Type"
heading[1] = "Group A"
heading[2] = "Groub B"
heading[3] = "Group C"
heading[4] = "Total"
var stock = new Array()
stock[0] = new Array("Cars", "88.625", "85.50", "85.81", "987")
stock[1] = new Array("Veggies", "88.625", "85.50", "85.81", "988")
stock[2] = new Array("Colors", "88.625", "85.50", "85.81", "989")
stock[3] = new Array("Numbers", "88.625", "85.50", "85.81", "990")
stock[4] = new Array("Requests", "88.625", "85.50", "85.81", "991")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < stock.length; i++) {
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td)
}
}
myTableDiv.appendChild(table)
}
</script>
</head>
<div id="metric_results">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
</div>
</body>
</html>
Change:
var tr = document.createElement('TR'); // this should be inside the first loop
tableBody.appendChild(tr); // this should be just before the first loop is over
for (i=0; i<stock.length; i++) {
for (j=0; j<stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td) // this should be tr.appendChild(td)
}
}
to this:
for (i = 0; i < stock.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
Fiddle

Combine HTML Table Rows with Javascript

Is there an easy way to combine rows in an HTML table where the first column is the same? I basically have a table set up like:
<table>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
</table>
and I want it to generate:
<table>
<tr><td>test</td><td>37035</td><td>37035</td><tr>
<tr><td>test2</td><td>24690</td><td>24690</td><tr>
</table>
using jQuery:
var map = {};
$('table tr').each(function(){
var $tr = $(this),
cells = $tr.find('td'),
mapTxt = cells.eq(0).text();
if(!map[mapTxt]){
map[mapTxt] = cells;
} else {
for(var i=1, l=cells.length; i<l; i++){
var cell = map[mapTxt].eq(i);
cell.text(parseInt(cell.text()) + parseInt(cells[i].text()));
}
$tr.remove();
}
});
this is a "dumb" script -- no error handling for cases like different number of cells, fields being non-numeric, etc. Add those if necessary.
Also, depending on how it's generated, it's better to do this server-side.
Here's a plain JavaScript version.
window.onload = function() {
var table = document.getElementById('mytable');
var tr = table.getElementsByTagName('tr');
var combined = Array();
for (i = 0; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var key = td[0].innerText;
if (!combined[key]) {//if not initialised
combined[key] = Array();
for (j = 0; j < td.length - 1; j++) combined[key][j] = 0;
}
for (j = 0; j < td.length - 1; j++)
combined[key][j] += parseInt(td[j + 1].innerText);
}
while (table.hasChildNodes()) table.removeChild(table.lastChild);
var tbody = document.createElement('tbody');//needed for IE
table.appendChild(tbody);
for (var i in combined) {
tr = document.createElement('tr');
tbody.appendChild(tr);
td = document.createElement('td');
td.innerText = i;
tr.appendChild(td);
for (j = 0; j < combined[i].length; j++) {
td = document.createElement('td');
td.innerText = combined[i][j];
tr.appendChild(td);
}
}
}
This will work on tables with any number of rows and any number of cells. I suppose you want to make the sum for every column, that's what this script does.
And as cwolves mentioned, it is more logical to do this serverside. Users that have JS disabled will see the not so clean uncombined table.

Categories