Why Javascript is not creating tables properly? - javascript

I am creating a program that connects to Firebase Realtime Database and displays the value in a table.
Her is my code:
var leadsRef = database.ref('leads/'+leadID);
var table = document.getElementById('remarksTable');
leadsRef.on('child_added', function(snapshot) {
var remark = snapshot.val().remark;
var timestamp = snapshot.val().timestamp;
var row = document.createElement('tr');
var rowData1 = document.createElement('td');
var rowData2 = document.createElement('td');
var rowData3 = document.createElement('td');
var rowDataText1 = document.createTextNode(remark);
var rowDataText2 = document.createTextNode(timestamp);
var rowDataText3 = document.createTextNode("Some text");
rowData1.appendChild(rowDataText1);
rowData2.appendChild(rowDataText2);
rowData3.appendChild(rowDataText3);
row.appendChild(rowData1);
row.appendChild(rowData2);
row.appendChild(rowData3);
table.appendChild(row);
});
leadID is an ID which I get from the current url, it contains the correct value so no issues there, path is also absolutely right.
Here is the table code:
<table class="table table-bordered" id="remarksTable">
<tr>
<th><strong>Created On</strong></th>
<th><strong>Timestamp 2</strong></th>
<th><strong>Remarks</strong></th>
</tr>
<tr>
<td>12312313231</td>
<td>12312312312</td>
<td>just a remark.</td>
</tr>
</table>
Now, when I run the page, it connects to the Firebase database and loads the required values, creates table row and table data, attaches text to it and then finally attaches the row to table with the id of remarksTable but it is not creating rows properly. Please note the table is creating using Bootstrap.
This is how it looks:
As you can see, the first row displays fine but the next 2 rows which were created by javascript looks a bit different.

The most likely reason is that you are appending the new row to the table element and not the tbody element inside it, which is interacting poorly with the stylesheet that you didn't include in the question.
Note that all tables have a tbody element. The start and end tags for it are optional so it will be inserted by HTML parsing rules if you don't provide one (or more) explicitly).

#Quentin is right, or you can simply add new rows this way:
var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData2 = row.insertCell(2);
rowData1.innerHTML = remark;
rowData2.innerHTML = timestamp;
rowData3.innerHTML = "some text";
Here is a working demo
function addCells() {
var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData3 = row.insertCell(2);
rowData1.innerHTML = "your remark";
rowData2.innerHTML = "your timestamp timestamp";
rowData3.innerHTML = "some text";
}
<table id="remarksTable" border=1>
<tr>
<td>first cell</td>
<td>2nd cell</td>
<td>3rd cell</td>
</tr>
</table>
<button onclick="addCells()">Add New</button>

Related

How can I add <td> tags to my html table with JavaScript?

I'm trying to use the insertcell method to add a column to my table but either I'm getting the syntax wrong or it isn't working. I wondered if anyone could explain where I am going wrong?
The table body in the html is populated dynamically with some other JavaScript but I don't think this is the problem as I've tested grabbing some content from that table with an alert box and it works (commented out below):
<!DOCTYPE html>
<script type="text/javascript" src="fullstationxyparser.js">
</script>
<html>
<body>
<table border=1>
<thead>
<tr>
<td>Element Name</td>
<td>x</td>
<td>y</td>
<td>testCol</td>
</tr>
</thead>
<tbody id="stationlist">
</tbody>
</table>
</body>
</html>
function addStationNames() {
var myTable = document.getElementById("stationlist");
var stationListRows = myTable.getElementsByTagName('tr');
for (var i = 1; i < stationListRows.length; i++) {
var cell = stationListRows[i].getElementsByTagName('td');
var stationName = cell[0].innerHTML; //get station id from element Name column
var currentRow = stationListRows[i];
var newCol = currentRow.insertcell(-1);
newCol.innerHTML = stationName;
//alert(stationName);
}
}
In Firefox developer tools, I get TypeError: "currentRow.insertcell is not a function". Perhaps I can't use the insertcell method on a row collection?
In general you can call the insertRow() method on a Table DOM element, followed by calls to the insertCell() method as shown below to dynamically add <td> tags to your table with JavaScript.
Be careful to call insertCell() (with capital C) rather than insertcell() as you are currently doing:
const table = document.querySelector('table');
/* Insert new row */
const row = table.insertRow();
/* Insert cells (td) for row */
const td0 = row.insertCell(0);
const td1 = row.insertCell(1);
const td2 = row.insertCell(2);
const td3 = row.insertCell(3);
/* Populate cells with data */
td0.innerText = 'Foo';
td1.innerText = '3';
td2.innerText = '6';
td3.innerText = 'success';
<table border="1">
<thead>
<tr>
<td>Element Name</td>
<td>x</td>
<td>y</td>
<td>testCol</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Specific to your code, some other changes to consider might be as listed in this code snippet:
function addStationNames() {
/* Condense table row access into single query */
const stationRows = document.querySelectorAll("#stationlist tr");
stationRows.forEach((stationRow, i) => {
/* Skip first row */
if(i === 0) { return; }
/* Get station name from text of first cell */
const stationName = stationRow.querySelector('td:first-child').innerText;
/* Insert last cell on row and assign station name */
stationRow.insertCell(-1).innerText = stationName;
});
/*
Old code:
for (let i = 1; i < stationListRows.length; i++) {
var cell = stationListRows[i].getElementsByTagName('td');
var stationName = cell[0].innerHTML;
var currentRow = stationListRows[i];
var newCol = currentRow.insertcell(-1);
newCol.innerHTML = stationName;
}
*/
}
addStationNames();
<!-- set table id to stationlist -->
<table border="1" id="stationlist">
<thead>
<tr>
<td>Element Name</td>
<td>x</td>
<td>y</td>
<td>testCol</td>
</tr>
<tr>
<td>90's pop</td>
<td>232</td>
<td>543</td>
</tr>
</thead>
<tbody>
<!-- Remove id from tbody -->
</tbody>
</table>
An alternative to the answer above (which is totally fine) is this method, which is also a more general method of creating any html element:
const table = document.getElementById('one');
const newRow = document.createElement("tr");
let newCell = document.createElement("td");
newCell.textContent = "first cell";
let newCell2 = document.createElement("td");
newCell2.textContent = "second cell";
newRow.appendChild(newCell);
newRow.appendChild(newCell2);
table.appendChild(newRow);
https://jsfiddle.net/zgaosdbv/

Insert html form data into the end of a table <tr> using vanilla Javascript

I created a javascript function that fires onSubmit and is supposed to take the input data and add it into a new row of a table on the same page.
I am not seeing any errors in my console. But the data is not making it to the table.
Below is my first try:
function addRow() {
// Get a reference to the table
let tableRef = document.getElementById('Job-table');
console.log(tableRef);
// Insert a row at the end of the table
let newRow = tableRef.insertRow(-1);
// Insert a cell in the row at index 0
let newCellJobName = newRow.insertCell(0);
let newCellJobDate = newRow.insertCell(1);
let newCellJobHost = newRow.insertCell(2);
// Below I is a test with a static string
//let newJobName = document.createTextNode("TEST 1");
//let newJobDate = document.createTextNode("TEST 2");
//let newJobHost = document.createTextNode("TEST 3");
// Append a text node to the cell
let newJobName = document.createTextNode(document.getElementById("JobName").value);
let newJobDate = document.createTextNode(document.getElementById("JobDate").value);
let newJobHost = document.createTextNode(document.getElementById("JobHost").value);
newCellJobName.appendChild(newJobName);
newCellJobDate.appendChild(newJobDate);
newCellJobHost.appendChild(newJobHost);
}
This is the HTML of my Table:
<table id="Job-table">
<tbody>
<tr><td>Test Job</td><td>12/05/2012</td><td>Mike Smith</td></tr>
<tr><td>Test Job</td><td>12/06/2012</td><td>Mike Smith</td></tr>
<tr><td>Test Job</td><td>12/07/2012</td><td>Mike Smith</td></tr>
</tbody>
</table>
I know there is an issue with the form input .value but I also tried to pass a static string and no luck there.
You can simple add it using inner html:
var inner = document.getElementById("Job-table").innerHTML;
document.getElementById("Job-table").innerHTML = inner + "<tr>...</tr>";
You are using a variable which isn't declared. Just change the line
newCellJobHost.appendChild(newJobAssigned);
to
newCellJobHost.appendChild(newJobHost);

Is it possible to hyperlink JavaScript array elements into an HTML table?

This is the code I have done so far. I want to hyperlink the websites so that when the array is outputted as a table in HTML, the websites will be clickable and link to their respective webpages. For some reason, the code in type="text/javascript" is different from the code in language="JavaScript" and I have no idea why. If someone could provide the code for language="JavaScript" that would be greatly appreciated!
HTML:
<table id="table">
<tr id="tbody">
<th>Mattress Type</th>
<th>Link</th>
</tr>
</table>
JAVASCRIPT:
<script language="JavaScript">
var table = document.getElementById("table");
var body = document.createElement("tbody");
var beds = new Array(3);
beds[0] = ["Spring Mattress", "King Size", "http://factorymattresstexas.com/specials/spring-air/"];
beds[1] = ["Rest Lumbar Support", "Queen Size", "http://factorymattresstexas.com/specials/beautyrest-lumbar-support"];
beds[2] = ["Beauty Rest", "Twin Size", "http://factorymattresstexas.com/specials/simmons-beautyrest/"];
table.appendChild(tbody);
beds.forEach(function(items) {
var row = document.createElement("tr");
items.forEach(function(item) {
var cell = document.createElement("td");
cell.textContent = item;
row.appendChild(cell);
});
table.appendChild(row);
});
</script>
You're almost there. You just need to continue adding child elements:
var table = document.getElementById("table");
var body = document.createElement("tbody");
// initialize an empty array
var beds = [];
// add bed objects to the array
beds.push({
type: "Spring Mattress",
size: "King Size",
link: "http://factorymattresstexas.com/specials/spring-air/"
});
beds.push({
type: "Rest Lumbar Support",
size: "Queen Size",
link: "http://factorymattresstexas.com/specials/beautyrest-lumbar-support"
});
beds.push({
type: "Beauty Rest",
size: "Twin Size",
link: "http://factorymattresstexas.com/specials/simmons-beautyrest/"
});
table.appendChild(tbody);
beds.forEach(function(item) {
var row = document.createElement("tr");
// You were previously just dumping the whole array contents in a cell. Most likely you want to have separate cells for each type of information.
var type = document.createElement("td");
type.textContent = item.type;
var size = document.createElement("td");
size.textContent = item.size;
// Create the containing cell to hold the link
var link_td = document.createElement("td");
// Create the ... element
var link = document.createElement("a");
link.textContent = item.link;
link.href = item.link
// Add the link to the cell
link_td.appendChild(link);
// Add the cells to the row in the order you'd like to see them in
row.appendChild(type);
row.appendChild(size);
row.appendChild(link);
table.appendChild(row);
});
<table id="table">
<tr id="tbody">
<th>Mattress Type</th>
<th>Size</th>
<th>Link</th>
</tr>
</table>
Update:
Your beds array was an array of array of strings. I switched this to use an array of bed objects. This allows you to define properties and reference those properties by name instead of by index (ie item.size vs item[1]). This is cleaner and will scale better as your codebase grows. You can extend the bed object with additional properties that you want to display.

Add table row programmatically doesn't work correctly in javascript

I have a form like that:
<form>
<table id="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>SVNr</th>
</tr>
<tr>
<td contenteditable="true">Jill</td>
<td contenteditable="true">Smith</td>
<td class="svnr" contenteditable="true">50</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
<tr>
<td contenteditable="true">Eve</td>
<td contenteditable="true">Jackson</td>
<td class="svnr" contenteditable="true">94</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
</table>
<input type="button" value="Save Changes">
</form>
This one works perfectly. Futhermore, I want to add table rows to my table programmatically.
I do it this way:
count = numberOfRows;
formular[count] = new Object();
formular[count]["Firstname"] = document.getElementById("Firstname").value;
formular[count]["Lastname"] = document.getElementById("Lastname").value;
formular[count]["SVNr"] = document.getElementById("SVNr").value;
var table = document.getElementById("table");
var TR = table.insertRow(count);
var TD = document.createElement("td");
TD.setAttribute("contenteditable", "true");
var TD2 = document.createElement("td");
TD2.setAttribute("contenteditable", "true");
var TD3 = document.createElement("td");
TD3.setAttribute("contenteditable", "true");
TD3.className = "svnr";
var TD4 = document.createElement("td");
var TXT = document.createTextNode(formular[count]["Firstname"]);
var TXT2 = document.createTextNode(formular[count]["Lastname"]);
var TXT3 = document.createTextNode(formular[count]["SVNr"]);
var Input = document.createElement("input");
Input.type = "submit";
Input.value = "Remove";
Input.onclick = "DeleteRow(this);";
TD.appendChild(TXT);
TR.appendChild(TD);
TD2.appendChild(TXT2);
TR.appendChild(TD2);
TD3.appendChild(TXT3);
TR.appendChild(TD3);
TD4.appendChild(Input);
TR.appendChild(TD4);
document.getElementById("Firstname").value = "";
document.getElementById("Lastname").value = "";
document.getElementById("SVNr").value = "";
Also this code is working well. The only problem is that the Remove function doesn't work correctly for the table rows I added programmatically.
My Removing function looks like that:
function DeleteRow(o) {
var p = o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
This function removes ALL programmatically added values if I press the button for one of them. This function works for the 2 entries in the form I didn't add programmatically but as I said, if I press the Remove button for one of added entries, it removes all programmatically added rows and not just the chosen one.
You need to add in something to uniquely identify each tr. You could set a custom attribute on each tr, set a unique id, etc. and pass the unique value to the delete function.
In addition you may find it easier to work with tables by using the DOMTable properties & methods:
http://www.javascriptkit.com/domref/tableproperties.shtml
http://www.javascriptkit.com/domref/tablemethods.shtml

Adding mousedown function in <tr> with javascript table creation not working

I am creating a html table using javascript as follows:
var table = document.getElementById("ordertable");
var rowcount = document.getElementById("ordertable").rows.length;
var row = table.insertRow(rowcount);
row.id="row_"+rowcount;
row.className = "rec_unselected";
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4)
I want to add a onmousedown function in in insertion step so I added like follows:
row.innerHTML = "onmousedown='RowClick(this,false);'";
But it is not working!
I am expecting the table like:
`<tr onmousedown="RowClick(this,false);" id="row_1" class="rec_unselected"`>
<td>any value</td>
<td>any value</td>
<td>any value</td>.....................
But I am getting as <tr id="row_1" class="rec_unselected">
Simply add your event listener with JavaScript by doing:
row.onmousedown = function(){ RowClick(this,false); }
What row.innerHTML = "onmousedown='RowClick(this,false);'" does is add that text into the element itself (and not as a onmousedown attribute event).
What you are trying to change is not the innerHTML. But since you are doing this in JS already, you should not move the function call to your HTML, but have it all in your scripts.
You add the click event to your row in JS like this:
row.addEventListener('mousedown', function (event) {
RowClick(event.target, false);
});

Categories

Resources