I am trying to insert rows into an html table with javascript. I have the table created and can add rows successfully with the click of a button. However, I want to be able to populate the rows with elements from several arrays on load. The button is just to make sure the rows are being added.
<html>
<input type="button" value="Add row" onclick="javascript:appendRow()" class="append_row"/>
<br/><br/></p>
<table id="my_table" align="center" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
</table>
<p></center></p>
<script type="text/javascript" language="javascript">
function appendRow(){
var names = ["Paul", "Mike", "Linda"];
var ages = ["16", "23", "44"];
var male_female = ["M", "M", "F"];
var tbl = document.getElementById('my_table'); // table reference
// append table row
var row = tbl.insertRow(tbl.rows.length);
// insert table cells to the new row
var row = tbl.insertRow();
for(var i=0;i<tbl.rows[0].cells.length;i++)
createCell(row.insertCell(i), i, 'row');
}
function createCell(cell, text, style){
var div = document.createElement('div'); // create DIV element
var txt = document.createTextNode(text); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('class', style); // set DIV class attribute
div.setAttribute('className', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
</script>
<style>
.row{background-color:#FFD6D6;width:43px;margin:3px;}
.col{background-color:#D6FFD6;width:43px;margin:3px;}
table#my_table{border-collapse:collapse;}
table#my_table td{width:50px;height:27px;border:1px solid #D3D3D3;font- size:10pt;text-align:center;padding:0;}
.append_row{background-color:#FFD6D6;border:1px #ccc solid;}
.append_column{background-color:#D6FFD6;border:1px #ccc solid;}
.delete{background-color:#eee;border:1px #ccc solid;}
</style>
</html>
In your for loop, try something like:
var j = tbl.rows.length - 1;
for (var i=0;i<tbl.rows[0].cells.length;i++) {
var cell_text = '';
if (i == 0) {
cell_text = name[j];
} else if (i == 1) {
cell_text = ages[j];
} else if (i == 2) {
cell_text = male_female[j];
}
createCell(row.insertCell(i), cell_text, 'row');
}
You forgot the "body" tag in the HTML syntax. You can put a call to your function in the onLoad variable, so it will be called after the page with loaded.
Related
I wrote a code to load data, adding and removing appended columns. However I am not able to remove the last header (of appended column). I managed to figure out to remove the first column header. Please see testing function. Is there a way to remove one cell header or removing a column with a header? The command
tbl.removeChild(tbl.firstChild);
removes only the first header of the first column. However, the code
tbl.removeChild(tbl.lastChild);
removes all data instead last header of the last appended column. What I am missing here?
Update: I managed to remove the last header but only once, next last column is removed but the header stay. Still, I am not able to solve the glitch. The code I modified is marked
Below is the complete code,
var flag1 = false;
var file = document.getElementById('inputfile');
var txtArr = [];
if (typeof(document.getElementsByTagName("table")[0]) != "undefined") {
document.getElementsByTagName("table")[0].remove();
}
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table"),
thead = document.createElement('thead');
var tblBody = document.createElement("tbody");
file.addEventListener('change', () => {
var fr = new FileReader();
fr.onload = function() {
// By lines
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
txtArr.push(lines[line].split(" "));
}
}
fr.readAsText(file.files[0]);
});
//console.log(flag1);
// document.getElementById('output').textContent=txtArr.join("");
//document.getElementById("output").innerHTML = txtArr[0];
// console.log(txtArr[2]);
function generate_table() {
// creating all cells
if (flag1 == false) {
th = document.createElement('th'),
th.innerHTML = "Name";
tbl.appendChild(th);
th = document.createElement('th');
th.innerHTML = "Sample1";
tbl.appendChild(th);
tbl.appendChild(thead);
tbl.appendChild(tblBody);
} //endif flag1=false
else {
th = document.createElement('th');
th.innerHTML = "Sample2";
tbl.appendChild(th);
tbl.appendChild(thead);
tbl.appendChild(tblBody);
}
for (var i = 0; i < txtArr.length - 1; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode(txtArr[i][j]);
cell.appendChild(cellText);
row.appendChild(cell);
tblBody.appendChild(row);
}
flag1 = true;
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
txtArr = [];
}
/////////// testing problems here /////////////////////
function testing() {
var i;
var lastCol = tbl.rows[0].cells.length - 1,
i, j;
// delete cells with index greater then 0 (for each row)
console.log(tbl.rows.length);
//while (tbl.hasChildNodes()) {
// tbl.removeChild(tbl.lastChild); // this line does not remove the last header
//}
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > lastCol - 1; j--) {
tbl.rows[i].deleteCell(j);
}
}
tbl.removeChild(thead); // this was updated
tbl.removeChild(th); // this was updated
// tbl.removeChild(tbl.firstChild); // this code remove only the first header
}
/////////// end of testing ////////////////////////////
function appendColumn() {
var i;
th = document.createElement('th');
th.innerHTML = "Sample";
tbl.appendChild(th);
tbl.appendChild(thead);
tbl.appendChild(tblBody);
// open loop for each row and append cell
for (i = 0; i < tbl.rows.length; i++) {
createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
}
}
// create DIV element and append to the table cell
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode(text); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('class', style); // set DIV class attribute
div.setAttribute('className', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
// delete table column with index greater then 0
function deleteColumn() {
var lastCol = tbl.rows[0].cells.length - 1,
i, j;
// delete cells with index greater then 0 (for each row)
console.log(tbl.rows.length);
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > lastCol - 1; j--) {
tbl.rows[i].deleteCell(j);
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Read Text File</title>
</head>
<body>
<input type="file" name="inputfile" id="inputfile">
<br>
<pre id="output"></pre>
<input type="button" value="Generate a table." onclick="generate_table()">
<input type="button" value="Add column" onclick="appendColumn()">
<input type="button" value="Delete column" onclick="deleteColumn()">
<input type="button" value="testing" onclick="testing()">
<table id="table">
</body>
</html>
You can loop over the rows and delete the last cell of each one.
for(const row of tbl.rows){
row.deleteCell(-1);
}
//or
[...tbl.rows].forEach(row => row.deleteCell(-1));
When I update an HTML table using appendChild(), the entire table is moved to the bottom of the document. How do I preserve the location of the table in the DOM?
My example is also posted on JSFiddle.
<!--I want the existing table below to stay fixed in place after new rows are added.-->
<table id="table">
<tr>
<td> Table Cell 1</td>
<td> Table Cell 2</td>
</tr>
</table>
<!--The following button will add rows, but also move the table. How do I stop the move?-->
<input type="button" value="ADD NEW ROWS." onclick="generate_table()">
<script>
// This function just creates new rows for the table
function generate_table() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.getElementById("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < 2; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode("cell " + i + ", column " + j);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
</script>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
Remove the following line, you don't need it.
body.appendChild(tbl);
The table node is already a part of the Document Object Model, you don't need to add it again. By appending the element to body, you are moving it from the current position to the end of the body node.
As a rule of thumb, you need to use appendChild, only if the element was created dynamically using createElement.
I am probably overthinking the question, but how do I restart a counter? Also, as you will see in my code, the counter is supposed to match but doesn't. I want the cell to have a shared value of the row that it is in, for example the first rows cells should have the ID: cell 0.0, cell 0.1, but rather it has skipped one where the first number is one row ahead.
var rowCount = 0;
var cellCount = 0;
function appendRow(id, style) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length); // append table row
row.setAttribute('id', style);
var i;
row.id = 'row' + rowCount;
rowCount++
console.log(rowCount, cellCount);
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + cellCount); // doesn't start over once row changes
cellCount++
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
}
td {
width: 100px;
}
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<div class="custScroll">
<table id="custListTop" contenteditable="false">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
</div>
I'm not sure this is what you want, but if you put rowCount++ after the for loop it starts off the first element at 0 then increments from there.
If you want the cells to start over then change createCell to use i instead of cellCount:
createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + i);
I'm trying to create a table in javascript and put a header on it. I tried to incorporate the answer from this SO question but perhaps I didn't include it in the right place. The body of the table works perfectly, but the header appends as a bunch of text to the top instead of a nicely formatted header. Here is the code:
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
var header = '<tr><th>Country</th><th>City</th></tr>';
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
tbl.append(header)
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
It prints the rows and the columns correctly, but instead of interpreting the <tr><th> as HTML tags it just prints them out as text. I've also noticed that if the table text contains any HTML tags, like <strong> or <b>, they are returned as plain text as well. How can I make them be read as HTML. I have a CSS page as well but there's no reset or anything (intentionally) affecting the use of bold or tables. Here's my result
<tr><th>Country</th><th>City</th></tr>
1 Row 1 text
2 Row <b>2</b> text
Solution1
The way you are appending tbody rows, you can insert the heading as well. So instead of tbl.append(header) and defining the header string, you can use something like below:
results = {
weak_sent: [
"row 1 data",
"row 2 data"
],
weak_sent_num: [1,2]
}
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
// var header = '<tr><th>Country</th><th>City</th></tr>';
var header= document.createElement('thead')
var headingRow = document.createElement('tr')
var headingCell1 = document.createElement('td')
var headingText1 = document.createTextNode('country')
headingCell1.appendChild(headingText1)
headingRow.appendChild(headingCell1)
var headingCell2 = document.createElement('td')
var headingText2 = document.createTextNode('City')
headingCell2.appendChild(headingText2)
headingRow.appendChild(headingCell2)
header.appendChild(headingRow)
tbl.appendChild(header)
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// This is for the quick solution
// tbl.innerHTML = header
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
generate_table()
Solution2
As a quick solution you can use innerHTML property, as shown below.
results = {
weak_sent: [
"row 1 data",
"row 2 data"
],
weak_sent_num: [1,2]
}
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
var header = '<tr><th>Country</th><th>City</th></tr>';
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// This is for the quick solution
tbl.innerHTML = header
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
generate_table()
I am creating a dynamic table of three columns and multiple rows. I want to be able to click the last cells in each row and have the row be selected showing a certain color. I am trying to do this as well as make sure that if another cell is selected already it will deselect. I am having a few issues not sure exactly what to do. I can create an onclick alert message that works, however no success with the bg color. Any suggestions are helpful. Function createCell should be where this is addressed.
<html>
<br/><br/></p>
<table id="my_table" align="center" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
</table>
<p></center></p>
<script type="text/javascript" language="javascript">
function appendRow(){
var names = ["Paul", "Mike", "Linda"];
var ages = ["16", "23", "44"];
var male_female = ["M", "M", "F"];
var tbl = document.getElementById('my_table'); // table reference
// append table row
var id;
var z=1;
for(k=0;k<names.length;k++){
var row = tbl.insertRow(tbl.rows.length);
var j = tbl.rows.length - 2;
for (var i=0;i<tbl.rows[0].cells.length;i++) {
id=z++;
var cell_text = '';
if (i == 0) {
cell_text = names[j];
} else if (i == 1) {
cell_text = ages[j];
} else if (i == 2) {
cell_text = male_female[j];
}
createCell(id, row.insertCell(i), cell_text, 'row');
}
}
}
function createCell(id, cell, text, style){
var div = document.createElement('div'); // create DIV element
var txt = document.createTextNode(text); // create text node
if(id % 3 == 0)
{
cell.setAttribute('onclick', 'alert("hello")'); //for testing purposes
cell.addEventListener("click", clickCell, false);
}
div.appendChild(txt); // append text node to the DIV
div.setAttribute('class', style); // set DIV class attribute
div.setAttribute('className', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
function clickCell()
{
if(e)
e.setAttribute("bgColor","purple");
if(e != this){
e = this;
e.setAttribute("bgColor","blue");
}else{
e = null;
}
}
</script>
<BODY onload="appendRow()">
<style>
table#my_table{border-collapse:collapse;}
table#my_table td{width:50px;height:27px;border:1px solid #D3D3D3;font-size:10pt;text-align:center;padding:0;}
.append_row{background-color:#FFD6D6;border:1px #ccc solid;}
</style>
</body>
</html>
Modify the clickCell method to:
function clickCell(e) {
// clear the background of all rows
var rows = document.getElementById('my_table').rows;
for(var i = 0; i < rows.length; i++) {
rows[i].style.backgroundColor = '';
}
// set background of clicked row
this.style.backgroundColor = 'purple';
}
See an example.
In createCell change cell.setAttribute('onclick', 'alert("hello")'); to cell.setAttribute('onclick', 'alert("hello");this.parentNode.setAttribute("bgcolor", "purple")');
Figured out that if I set the clickcell function to the following, it will clear all cells that are colored. I thought I could call "this.style.backgroundColor" to change the cell color and then clear that cell with a "row.style.backgroundColor" turns out I was wrong.
function clickCell(e) {
var tr = document.getElementById('my_table').rows;
for(i=0;i<tr.length;i++)
{
for(k=0;k<tr[i].cells.length;k++)
{
tr[i].cells[k].style.backgroundColor = "";
}
}
this.style.backgroundColor = "blue";
}