Create table using Javascript from JSON [duplicate] - javascript

This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 8 years ago.
I have data in an object that I'm trying to display in a table. Unfortunately, all my columns are displaying undefined.
var fifadata = [{
"fields": ["id", "country", "alternate_name", "fifa_code", "group_id", "group_letter", "wins", "draws", "losses", "games_played", "points", "goals_for", "goals_against", "goal_differential"]
}, {
"id": 1,
"country": "Brazil",
"alternate_name": null,
"fifa_code": "BRA",
"group_id": 1,
"group_letter": "A",
"wins": 4,
"draws": 1,
"losses": 2,
"games_played": 7,
"points": 13,
"goals_for": 11,
"goals_against": 14,
"goal_differential": -3
}, {
"id": 2,
"country": "Croatia",
"alternate_name": null,
"fifa_code": "CRO",
"group_id": 1,
"group_letter": "A",
"wins": 1,
"draws": 0,
"losses": 2,
"games_played": 3,
"points": 3,
"goals_for": 6,
"goals_against": 6,
"goal_differential": 0
}, {
"id": 3,
"country": "Mexico",
"alternate_name": null,
"fifa_code": "MEX",
"group_id": 1,
"group_letter": "A",
"wins": 2,
"draws": 1,
"losses": 1,
"games_played": 4,
"points": 7,
"goals_for": 5,
"goals_against": 3,
"goal_differential": 2
}];
var body = document.getElementsByTagName('body')[0];
var table = document.createElement("table");
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var th = document.createElement("th");
var caption = document.createElement('caption');
var cap = document.createTextNode("Game Results List");
caption.appendChild(cap);
caption.style.fontWeight = "900";
table.appendChild(caption);
body.appendChild(table);
table.style.border = "1px dashed red";
table.style.borderSpacing = "1px";
table.style.textAlign = "center";
//table head(correct)
for (i = 0; i < 1; i++) {
var tr = document.createElement("tr");
thead.appendChild(tr);
table.appendChild(thead);
for (j = 0; j < fifadata[0].fields.length; j++) {
var th = document.createElement("th");
var keyname = fifadata[0].fields[j];
var tm = document.createTextNode(keyname);
th.appendChild(tm);
tr.appendChild(th);
th.style.border = "1px dashed blue";
th.style.padding = "5px";
}
}
//table body(incorrect).
//I need to use a dynamically created property(i.e. keyinfo) in "var text"
//i.e.fifadata[i].keyinfo; should change into fifadata[1].ID when it is
//excecuted.
for (i = 1; i < fifadata.length; i++) {
var tr = document.createElement("tr");
tbody.appendChild(tr);
table.appendChild(tbody);
for (j = 0; j < fifadata[0].fields.length; j++) {
var td = document.createElement("td");
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i].keyinfo;
var tn = document.createTextNode(test);
td.appendChild(tn);
tr.appendChild(td);
td.style.border = "1px dashed green";
td.style.padding = "2px";
}
}
If all goes well it should create a table from the JSON data. Can my code be modified slightly? Is there an easier why to do it?

You can't use variables like that in dot notation. You're essentially asking for a property named keyinfo, which doesn't exist.
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i].keyinfo; // wrong
To access the property whose name is keyinfo's value, you'll need to use bracket notation, like so:
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i][keyinfo]; // right
Have a look at this simplified demo:
(function() {
// loading data from a hidden input to declutter the demo script
var fifadata = JSON.parse(document.getElementById("fifadata").value);
var table = document.createElement("table");
var thead = table.appendChild(document.createElement("thead"));
var tbody = table.appendChild(document.createElement("tbody"));
var row = thead.insertRow(-1);
// remove the first item in fifadata and get a reference to its fields property
var fieldNames = fifadata.shift().fields;
// create column headers
fieldNames.forEach(function(fieldName) {
row.appendChild(document.createElement("th")).textContent = fieldName;
});
// populate tbody rows
fifadata.forEach(function(record) {
row = tbody.insertRow(-1);
fieldNames.forEach(function(fieldName) {
// note that we use bracket notation to access the property
row.insertCell(-1).textContent = record[fieldName];
});
});
// add the table to the body once fully constructed
document.body.appendChild(table);
})();
<input type="hidden" id="fifadata" value='[{"fields":["id","country","alternate_name","fifa_code","group_id","group_letter","wins","draws","losses","games_played","points","goals_for","goals_against","goal_differential"]},{"id":1,"country":"Brazil","alternate_name":null,"fifa_code":"BRA","group_id":1,"group_letter":"A","wins":4,"draws":1,"losses":2,"games_played":7,"points":13,"goals_for":11,"goals_against":14,"goal_differential":-3},{"id":2,"country":"Croatia","alternate_name":null,"fifa_code":"CRO","group_id":1,"group_letter":"A","wins":1,"draws":0,"losses":2,"games_played":3,"points":3,"goals_for":6,"goals_against":6,"goal_differential":0},{"id":3,"country":"Mexico","alternate_name":null,"fifa_code":"MEX","group_id":1,"group_letter":"A","wins":2,"draws":1,"losses":1,"games_played":4,"points":7,"goals_for":5,"goals_against":3,"goal_differential":2}]'/>
See also: Property Accessors, Array.prototype.forEach(), Array.prototype.shift(), HTMLTableElement.insertRow(), HTMLTableRowElement.insertCell(), and Node.textContent

Related

How to add clickable text in dynamically created table in JS

I have a dynamically generated table based on JSON response. The table has 3 columns - 1 for S. No., 2 for Name, and 3 is supposed to have two text links like Edit | Delete.
Edit and Delete are supposed to be clickable individually and upon clicking them I want to retrieve the respective JSON object to be able to process it further.
Example -
JSON response:
[
{
"id": 2,
"owner": 1,
"name": "General"
},
{
"id": 3,
"owner": 1,
"name": "Specific"
},
{
"id": 10,
"owner": 1,
"name": "One more"
},
{
"id": 11,
"owner": 1,
"name": "Test Category"
}
]
JS to generate table from the above JSON data:
function populateTable(data) {
const resLen = data.length;
var col = [];
col.push("S. No.");
for (var i=0; i<data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1 && key == "name") {
col.push(key);
}
}
}
col.push(" ");
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i=0; i<col.length; i++) {
var th = document.createElement("th");
if (col[i] == "name") {
th.innerHTML = "Name";
tr.appendChild(th);
} else {
th.innerHTML = col[i];
tr.appendChild(th);
}
}
for (var i=data.length-1; i>=0; i--) {
tr = table.insertRow(-1);
for (var j=0; j<col.length; j++) {
var tabCell = tr.insertCell(-1);
if (j == 0) {
tabCell.innerHTML = ((data.length-1) - i)+1;
} else if (j == 2) {
tabCell.innerHTML = "Delete"
} else {
tabCell.innerHTML = data[i][col[j]];
}
}
}
var divContainer = document.getElementById("categoriesTable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
Visual of the table:
I want to add clickable text in the third column (where currenlty Delete is) such that when I click on the text, I can retrieve its related JSON object and extract the id. I would like to do this in plain JS and HTML.
at first i suggest you using helper libraries like jquery(https://jquery.com) to have a better life but if you prefer pure javascript to attach event to dynamic created elements, your answer is event delegation which is answered in this post:
Attach event to dynamic elements in javascript
With jquery:
inside td tag, use button or link tag as delete button
add a css class(class="btn_delete") with a referal attribute to keep row id(data-rowid="25")
add jquery code
$(document).on('click','.btn_delete',function(){var rowid=$(this).data('rowid');//do something else ... });
You can use a html a tag:
text

Trying to convert the JSON file to an HTML Table using jQuery

I am trying to convert the Array to an HTML Table using jQuery. However, the browser shows nothing from the JSON file. Please see my codes below.
JSON file
[
{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
HTML and JS
<script>
$(document).ready(function () {
$.getJSON("result.json", function (data) {
var arrItems = []; // THE ARRAY TO STORE JSON ITEMS.
$.each(data, function (index, value) {
arrItems.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
});
// EXTRACT VALUE FOR TABLE HEADER.
var col = [];
for (var i = 0; i < arrItems.length; i++) {
for (var key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < arrItems.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
});
Hi gusy, I am trying to convert the Array to an HTML Table using jQuery. However, the browser shows nothing from the JSON file. Please see my codes below.

Function not running on button click? [duplicate]

This question already has answers here:
Is "clear" a reserved word in Javascript?
(4 answers)
Closed 6 years ago.
I have a button on my page that is intended to clear all the textareas that are in the document, however when I click said button it appears that the function isn't being run. I've tried adding a button listener to the document, and that still didn't seem to work, I don't understand what the problem is, as the line with the alert isn't even running.
function markForm(tagID) {
var x = document.getElementById(tagID)
var pre = document.createElement("pre");
x.appendChild(pre);
var SectionDetails = [
{ name: "Dynamic Table", maxMarks: 20},
{ name: "IntelliJ usage", maxMarks: 10},
{ name: "Calendar Controller", maxMarks: 30},
{ name: "Active Form", maxMarks: 20},
{ name: "Object Database", maxMarks: 20}
];
var table = pre.appendChild(document.createElement("table"));
var tableHeader = table.appendChild(document.createElement("thead"));
var tableRow = tableHeader.appendChild(document.createElement("tr"));
var headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Section"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Max Mark"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Comments"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Mark"));
var resultsRows = table.appendChild(document.createElement("tbody"));
for (var i = 0; i < SectionDetails.length; i++) {
tableRow = resultsRows.appendChild(document.createElement("tr"));
var tableData = tableRow.appendChild(document.createElement("td"));
tableData.appendChild(document.createTextNode(SectionDetails[i].name));
tableData = tableRow.appendChild(document.createElement("td"));
tableData.appendChild(document.createTextNode(SectionDetails[i].maxMarks));
tableData = tableRow.appendChild(document.createElement("td"));
var tarea = document.createElement("textarea");
tarea.value = "Enter Comments";
tableData.appendChild(tarea);
tableData = tableRow.appendChild(document.createElement("td"));
var dropDown = document.createElement("select");
dropDown.name = SectionDetails[i].name;
for (var j = 0; j < (SectionDetails[i].maxMarks + 1); j++) {
var listItem = new Option(j);
listItem.value=j;
dropDown.appendChild(listItem);
}
tableData.appendChild(dropDown);
}
var h2 = document.createElement("h2");
h2.innerHTML = "Total Marks: " + document.createTextNode(totalMarks);
x.appendChild(h2);
}
function totalMarks() {
var total = 0;
for (var a = 0; a < SectionDetails.length; a++) {
var e = document.getElementById(SectionDetails[a].name);
var total = total + Number(e.options[e.selectedIndex].value);
}
return total;
}
function clear() {
var textareas = documents.getElementsByTagName("textarea");
console.log(textareas);
for (var i = 0; i < textareas.length; i++) {
textareas[i].value="Enter Comments";
}
alert("Fields Cleared");
}
<body onload="markForm('conversion')">
<h2>Marking Form: </h2>
<p id='conversion'>
</p>
<p id='clear'>
<input type="button" id="but" value="Clear" onclick="clear()"/>
</p>
There seems an error in your clear() function. it should be document.getElementsByTagName(). and yours is "documents" - also clear is a word used elsewhere: document.clear

Giving unique id to table cell

I have created a table.
I have text input where I type some text. It refers to some element with special values.
When I click a button the productname is added to the table (using insertCell()).
I want to give a unique id to every new table element.
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value; // text input
var table = document.getElementById("pos1"); // button near text input
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
row = table.insertRow(2);
var c_id = 0;
for (var i = 0; i < p.length ; i++) {
cell = row.insertCell(i);
cell.innerHTML = p[i];
for (var j = 0; j < 1 ; j++) {
cell.id = 'tdp1' + k_id;
c_id++;
}
} // It only works for one element, and the others have the same id as elements from row1
}
a. There seems to be a type in the line cell.id = 'tdp1' + k_id; It is supposed to be c_id instead of k_id
b. You do not need the second for loop for anything and just can remove it.
The following code gives me a new row with ids for each cell (tdp10 to tdp15)
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value; // text input
var table = document.getElementById("pos1"); // button near text input
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
row = table.insertRow(2);
var c_id = 0;
for(var i = 0; i < p.length ; i++){
cell = row.insertCell(i);
cell.innerHTML = p[i];
cell.id = 'tdp1' + c_id;
c_id++;
}
}
I found solution:
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value;
var table = document.getElementById("pos1");
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
var cells = document.getElementsByClassName("pos");
row = table.insertRow(2);
for(var i = 0; i < p.length ; i++){
cell = row.insertCell(i);
cell.innerHTML = p[i];
cell.className = "pos";
for(var j = 0; j < cells.length ; j++){
cell.id = 'tdp1' + j;
}
}
I gave created cell a className. It's working, but thank you for help. :)

Putting my Javascript arrays into a table

With my program I am taking these values. Checking to see if they match and summarizing them. I have everything working except all my attempts to take the final data and put it into an table have failed.
I want to have the table be three rows and four columns. Each of the rows will be one of the finished arrays. Starting with the product name on the left and moving right per column
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script language="javascript" type="text/javascript">
var finished1 = ["Firex","Enrique",0,0];
var finished2 = ["Detector","Chris",0,0];
var finished3 = ["Hpvv","Diana",0,0];
var info = [];
info.push(["Firex", "Enrique", 6, 20000]);
info.push(["Detector", "Chris", 7, 35000]);
info.push(["Hpvv", "Diana", 12, 10000]);
info.push(["Firex", "Enrique", 4, 25000]);
info.push(["Detector", "Chris", 3, 15000]);
info.push(["Hpvv", "Diana", 3, 30000]);
info.push(["Firex", "Enrique", 8, 10000]);
info.push(["Detector", "Chris", 5, 20000]);
info.push(["Hpvv", "Diana", 6, 15000]);
info.push(["Firex", "Enrique", 5, 25000]);
info.push(["Detector", "Chris", 6, 35000]);
info.push(["Hpvv", "Diana", 7, 35000]);
info.push(["Firex", "Enrique", 3, 40000]);
info.push(["Detector", "Chris", 9, 10000]);
info.push(["Hpvv", "Diana", 5, 15000]);
info.forEach(function(element, index, array) {
if(array[0][0] === array[index][0]) {
finished1[2] += array[index][2];
finished1[3] += array[index][3];
}
else if(info[1][0] === info[index][0]) {
finished2[2] += array[index][2];
finished2[3] += array[index][3];
}
else if(info[2][0] === info[index][0]) {
finished3[2] += array[index][2];
finished3[3] += array[index][3];
}
});
console.log(finished1);
console.log(finished2);
console.log(finished3);
</script>
</body>
</html>
It's better if you create the table programmatically using DOM api, as #rlemon said.
//create the table DOM element
var table = document.createElement('table');
//create a row
var tr = document.createElement('tr');
//optional - adds headers to table
for(var x = 0; x < 4; x++){
//create table header element
var th = document.createElement('th');
//set element text
th.innerText = "header"+x;
//append cell to row
tr.appendChild(th);
}
//appends row to table
table.appendChild(tr);
//create another row
tr = document.createElement('tr');
for(var x = 0; x < 4; x++){
//create cell
var td = document.createElement('td');
//set cell text
td.innerText = finished1[x];
tr.style.backgroundColor = "#AAA";//a little bit of color
//append cell to row
tr.appendChild(td);
}
table.appendChild(tr);
tr = document.createElement('tr');
for(var x = 0; x < 4; x++){
var td = document.createElement('td');
td.innerText = finished2[x];
tr.appendChild(td);
}
table.appendChild(tr);
tr = document.createElement('tr');
for(var x = 0; x < 4; x++){
var td = document.createElement('td');
td.innerText = finished3[x];
tr.style.backgroundColor = "#AAA";
tr.appendChild(td);
}
table.appendChild(tr);
//append table to body
document.body.appendChild(table);
As #zipzit suggested you can use document.write to accomplish displaying your data on the page. You can write your html along with your data as a string in JavaScript like so:
var createTable = '<table><tr><td>' + finished1 + '</td></tr>' + '<tr><td>' + finished2 + '</td></tr>' + '<tr><td>' + finished3 + '</td></tr>' + '</table>'
And then utilize document.write to display that string on the page.
document.write(createTable);
Check out these docs on creating tables in html in order to add your desired table headers and other styling.

Categories