How can I create an HTML table from a JavaScript object? - javascript

I want to create an html table. It should have two columns and x amount of rows.
var row = 1;
var test = [{
device: "deviceA",
tasks: ["task1", "task2", "task3", "task5"]
}]
var display = document.getElementById("device=table-body");
var newRow = display.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
cell1.innerHTML = test[0]["device"]
cell2.innerHTML = test[0]["device"]
<table id="device=table-body"></table>
I tried the code above, but it's not displaying anything. Not sure where I'm going wrong. End goal is below:
device. || Task
----------------
deviceA || Task1
task2
----------------
deviceB || task1

As you can see, there's a console error:
The index provided (1) is greater than the number of rows in the table (0). Set your variable to 0.
var row = 0;
var test = [{
device: "deviceA",
tasks: ["task1", "task2", "task3", "task5"]
}]
var display = document.getElementById("device=table-body");
var newRow = display.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
cell1.innerHTML = test[0]["device"]
cell2.innerHTML = test[0]["device"]
<table id="device=table-body"></table>

do you have a row inside your table ? if no, replace your variable row value to 0 or -1.
const addRow = id => {
var test = [{
device: "deviceA",
tasks: ["task1", "task2", "task3", "task5"]
}]
// Get Table by name
var display = document.getElementById(id);
// Insert a row at the end of the table
var newRow = display.insertRow(-1);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
cell1.innerHTML = test[0]["device"];
cell2.innerHTML = test[0]["device"];
};
addRow("myTable");
td {
border: 1px solid black;
}
<table id="myTable">
</table>

Related

Managing elements of a dynamicly produced table

A button , onclick , adds a table row with three cells. In the first cell theres a textbox where you input an image url, the second cell contains a button.When pressed the button shows the image that the url refers to on the third cell.
Doing this for one row is simply, but i cant get it to work for subsequent rows because the id of each element would remain the same.
I need some tips and ideas.
Code sample:
<script>
var u = 1;
function addRows() {
var table = document.getElementById("t1");
var row = table.insertRow(u);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = '<input id="ur" type="url" >';
cell2.innerHTML = '<button onclick="document.getElementById(\'im1\').src = document.getElementById(\'ur\').value;">Add Image</button>';
cell3.innerHTML = '<img id="im1" src="" alt="image">';
u++;
}
</script>
Each row generates fine and if you put in a url or the name of a local image file it will display properly on the third cell.
But it only works on the first generated row.
With this sort of thing you shouldn't be calling and duplicating ids but instead relying on Sibling properties. Nevertheless a quick hack would be to use your increment variable to give unique ids to the elements.
var u = 1;
function addRows(){
var table = document.getElementById("t1");
var row = table.insertRow(u);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = '<input id="ur'+u'" type="url" >' ;
cell2.innerHTML = '<button onclick="document.getElementById(\'im'+u'\').src = document.getElementById(\'ur'+u+'\').value;">Add Image</button>' ;
cell3.innerHTML = '<img id="im'+u+'" src="" alt="image">' ;
u++;
}
</script>
This should work:
function addRow() {
var table = document.getElementById("tab");
var row = document.createElement("tr");
var buttonTd = document.createElement("td");
var button = document.createElement("button");
button.type = "button";
button.innerHTML = "Show image";
buttonTd.appendChild(button);
var textboxTd = document.createElement("td");
var textbox = document.createElement("input");
textbox.type = "text";
textboxTd.appendChild(textbox);
var imageTd = document.createElement("td");
var image = document.createElement("img");
imageTd.appendChild(image);
row.appendChild(textboxTd);
row.appendChild(buttonTd);
row.appendChild(imageTd);
button.addEventListener("mousedown", function () {
image.src = textbox.value;
});
table.appendChild(row);
}
table,tr,td {
border: 1px solid black;
border-collapse: collapse;
}
<button onclick="addRow()">Add Row</button>
<table id="tab"></table>

TypeError: table is null when adding row to table

I am Trying to create and add elements to a table.
function flaeche() {
let tableID = "testTable";
let x = document.createElement("TABLE");
x.setAttribute("id", tableID);
for (let argument of arguments) {
let radius = ((argument*argument)*Math.PI).toFixed(2);
addRow(argument,radius,tableID);
}
}
function addRow(value, result, tableID){
let table = document.getElementById(tableID);
let row = table.insertRow(0);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
cell1.innerHTML = value;
cell2.innerHTML = result;
}
If I try to run the code I get the following error:
TypeError: table is null at addRow line 30:5
which corresponds to
let table = document.getElementById(tableID);
I really have no idea why it says so since I am fairly new to JavaScript. I appreciate your help.
You are making a table element, but you aren't adding it to the page. You need to actually put the table somewhere in the DOM if you want to find it with document.getElementById() later. For example:
function flaeche() {
let tableID = "testTable";
let x = document.createElement("TABLE");
x.setAttribute("id", tableID);
// add table to the page somewhere
// for example in the div named container
let container = document.getElementById("container")
container.appendChild(x)
for (let argument of arguments) {
let radius = ((argument*argument)*Math.PI).toFixed(2);
addRow(argument,radius,tableID);
}
}
function addRow(value, result, tableID){
let table = document.getElementById(tableID);
let row = table.insertRow(0);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
cell1.innerHTML = value;
cell2.innerHTML = result;
}
flaeche(5, 6)
td {
border: 1px solid #ddd;
padding: 1em;
}
<div id="container"></div>

Correct the serial numbers of the row after deletion using Javascript only

I have two functions for adding and deleting rows in a table using Javascript:
function addRow() {
//document.getElementById("div_dea").style.display = "none";
document.getElementById("div_orderlist").style.display = "block";
var table = document.getElementById("ordertable");
var rowcount = document.getElementById("ordertable").rows.length;
var row = table.insertRow(rowcount);
row.id="row_"+rowcount;
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
var sel = document.getElementById("select_product_name");
var optiontext = sel.options[sel.selectedIndex].text;
cell1.innerHTML = rowcount;
cell2.innerHTML = optiontext;
cell3.innerHTML = "abc";
}
Delete Row as follows:
function deleteRow(){
var table = document.getElementById("ordertable");
var rowcount = document.getElementById("ordertable").rows.length;
alert("first"+rowcount);
for(var i=1;i<rowcount;i++){
row = table.rows[i];
if(document.getElementById(row.id).style.backgroundColor =="red"){
table.deleteRow(row.rowIndex);
}
}
alert("second"+rowcount);
}
While addRow() I am adding serial numbers as: cell1.innerHTML = rowcount;
I need correct the serial numbers after deletion:
The rows get deleted But alert("second"+rowcount); not even working in deletion. How can correct the serial numbers of row after deletion.
Note: Use JavaScript only
Use this code
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++){
table.rows[i].cells[0].innerHTML=i;
}}

Add OnClick Event with JavaScript or CSS

I have a table in HTML:
<table id="cust">
<tr>
<th>UserName</th>
<th>Password</th>
</tr>
<script type="text/javascript">addRows();</script>
</table>
and I have function in JS that insert Rows to this table. for example:
function addRows() {
// Get a reference to the table
var table = document.getElementById("cust");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "ilan";
cell1.innerHTML = "11111";
}
but I want that every row that insert to the table, will be with onClick event like that:
<tr onclick="window.document.location='Accounts.html';">
how can I do that?
thank you !!
You can use this-
row.setAttribute("onclick","window.document.location='Accounts.html'");
function addRows() {
// Get a reference to the table
var table = document.getElementById("cust");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.setAttribute("onclick","window.document.location='Accounts.html'");
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "ilan";
cell1.innerHTML = "11111";
}
Since you are not using any jQuery constructs add a onlick handler to the row element
function addRows() {
// Get a reference to the table
var table = document.getElementById("cust");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.onclick = rowClick
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "ilan";
cell1.innerHTML = "11111";
}
function rowClick() {
window.document.location = 'Accounts.html';
}
If you want to have different target locations then
function addRows() {
// Get a reference to the table
var table = document.getElementById("cust");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.onclick=function(){
window.document.location='Accounts.html';
}
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "ilan";
cell1.innerHTML = "11111";
}

Dynamically creating table rows and div's using document.createElement(“div”);

I am trying to dynamically parse JSON data and populate the data in rows in an html table.
I wrote the following test and don't really see any reason why it should not work.
EDIT:corrected the two syntax errors.
<tohead>
<script>
var zoho = "?({"Products":[{"model":"UN55F8000BFXZA","phone":"1234567890","price":"2999.99","manufacturer":"Samsung","purchaseDate":"2013-07-26"}]});"
$(document).ready(function(){
processRecord(zoho);
});
function addRow(inc) {
VAR table = document.getElementById("dataTable");
VAR rowCount = table.rows.length;
VAR row = table.insertRow(rowCount);
VAR cell1 = row.insertCell(0);
VAR element1 = document.createElement("div");
element1.id = 'manufacturer' + inc;
element1.class = "text";
cell1.appendChild(element1);
VAR cell2 = row.insertCell(1);
VAR element2 = document.createElement("div");
element2.id = 'purchaseDate' + inc;
element2.class = "text";
element2.align = "center";
cell2.appendChild(element2);
VAR cell3 = row.insertCell(2);
VAR element3 = document.createElement("div");
element3.id = 'endingDate' + inc;
element3.class = "text";
element3.align = "center";
cell3.appendChild(element3);
};
function processRecord(zoho_data){
for (var i=0; i<zoho_data.length; i++){
addRow(i);
var phonenumber = zoho_data.Products[i].phone;
var zmanufacturer = zoho_data.Products[i].manufacturer;
var zmodel = zoho_data.Products[i].model;
var zpurchaseDate = zoho_data.Products[i].purchaseDate;
document.getElementById('manufacturer' + i).appendChild(zmanufacturer);
document.getElementById('purchaseDate' + i).appendChild(zpurchaseDate);
document.getElementById('endingDate' + i).appendChild(d1);
}
};
</script>
</tohead>
<HTML>
<HEAD>
</HEAD>
<BODY>
<TABLE id="dataTable" width="546">
</TABLE>
</BODY>
</HTML>
EDIT: In response to the comments I have reduced the complexity of the code above to narrow down the issue. The code below is the new code with just the createElement loop.
<HTML>
<HEAD>
<script>
$(document).ready(function(){
addRow();
});
function addRow() {
for (var i=0; i<4; i++)
{
VAR table = document.getElementById("dataTable");
VAR rowCount = table.rows.length;
VAR row = table.insertRow(rowCount);
VAR cell1 = row.insertCell(0);
VAR element1 = document.createElement("div");
element1.setAttribute('id', 'manufacturer' + i);
element1.setAttribute(class, 'text');
cell1.appendChild(element1);
VAR cell2 = row.insertCell(1);
VAR element2 = document.createElement("div");
element2.setAttribute('id', 'purchaseDate' + i);
element2.setAttribute(class, 'text');
element2.setAttribute(align, 'center');
cell2.appendChild(element2);
VAR cell3 = row.insertCell(2);
VAR element3 = document.createElement("div");
element3.setAttribute('id', 'endingDate' + i);
element3.setAttribute(class, 'text');
element3.setAttribute(align, 'center');
cell3.appendChild(element3);
}
};
</script>
</HEAD>
<BODY>
<TABLE id="dataTable" width="546" border="1">
<tr>
<td>boo</td>
</tr>
</TABLE>
</BODY>
</HTML>
Your zoho string is not an object, but a string, and as it starts with ?( it is not valid JSON. It is not even valid Javascript — just look at those errant quotation marks.
You need to fix your JSON so that it is valid JSON, and then you need to convert your JSON string into a Javascript object.
Then, you need to fix document.getElementById(dataTable) because no such variable dataTable exists in your program. Did you mean the string "dataTable"?
appendChild only works with actual DOM type one nodes. Since it looks like you're just appending string values, try using textContent =
See: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild
If you want to append them as their own elements, you'll need to use: document.createElement so that appendChild will work (since it belongs to the Node object).
For the benefit of anyone who might see this and have a similar concern. The correct code is below. I am passing in the function data returned in JSON format parsing it, and writing it to dynamically created "div"s, inside dynamically created table rows.
function processData(zoho_data){
$.each(zoho_data.Products, function() {
var phonenumber = this.phone;
var zmanufacturer = this.manufacturer;
var zmodel = this.model;
var zpurchaseDate = this.purchaseDate;
var d1 = Date.parse(zpurchaseDate).add(4).year().toString('yyyy-MM-dd');
var table = document.getElementById("datatable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(-1);
var element1 = document.createElement("div");
element1.setAttribute('class', 'text');
cell1.innerHTML = zmanufacturer + " " + zmodel;
cell1.appendChild(element1);
var cell2 = row.insertCell(-1);
var element2 = document.createElement("div");
element2.setAttribute('class', 'text');
element2.setAttribute('align', 'center');
cell2.innerHTML = zpurchaseDate;
cell2.appendChild(element2);
var cell3 = row.insertCell(-1);
var element3 = document.createElement("div");
element3.setAttribute('class', 'text');
element3.setAttribute('align', 'center');
cell3.innerHTML = d1;
cell3.appendChild(element3);
});
};

Categories

Resources