i have a json code incomming in my html file and i am trying to add table rows to the top of a html table in a basic .html file via javascript
heres my javascript code:
var data = json.data;
for (var i = 0, len = data.length; i < len; i++) {
var x = data[i];
var newItem = document.createElement("tr");
var textnode = document.innerHTML = '<th scope="row"> ' + x.granularity + '</th> <td> ' + x.instrument + '</td> <td>complete: ' + x.complete + ', type: ' + x.type + ', alerttimedate: ' + x.alerttimedate + ', firsttopbot: ' + x.firsttopbot + ', alertprice: ' + x.alertprice + ', firsttbprice: ' + x.firsttbprice + ', timestamp: ' + x.timestamp + ', proceesed: ' + x.proceesed + '</td>';
newItem.appendChild(textnode);
var list = document.getElementById("myList");
list.insertBefore(newItem, list.childNodes[0]);
}
heres the table in html file:
<table class="table table-striped" id="myList">
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
</table>
the var textnode = document.innerHTML content does not add any elements to my html file??
any ideas what I am doing wrong here?
json data comes from a php fil in this format
foreach ($result as $row) {
$output[] = [
'instrument' => $row['instrument'],
'granularity' => $row['granularity'],
'complete' => $row['complete'],
'type' => $row['type'],
'alerttimedate' => $row['alerttimedate'],
'firsttopbot' => $row['firsttopbot'],
'alertprice' => $row['alertprice'],
'firsttbprice' => $row['firsttbprice'],
'timestamp' => $row['timestamp'],
'proceesed' => $row['proceesed']];
$lastId = $row['id'];
}
echo json_encode([
'status' => true,
'data' => $output
]);
As I am not sure about what you actually need, due to the lack of coding, I've developed a demo to your problem (as far as I understood it)
// Placeholder JSON data
var data = {
instrument: 'val1',
granularity: 'val2',
complete: 'val3',
type: 'val4',
alerttimedate: 'val5',
firsttopbot: 'val6',
alertprice: 'val7',
firsttbprice: 'val8',
timestamp: 'val9',
proceesed: 'val10'
}
// Select the table
var tableData = document.querySelector("#tableData")
// Creating the `tr`s
var trHead = document.createElement("tr")
var trData = document.createElement("tr")
// Add the data
for (var key in data) {
if (data.hasOwnProperty(key)) {
// Create th
var th = document.createElement("th")
th.innerText = key
// Create td
var td = document.createElement("td")
td.innerText = data[key]
// Append the `td` & `th` to the `tr`s
trHead.appendChild(th)
trData.appendChild(td)
}
}
// Append both `tr`s to the `table`
tableData.appendChild(trHead)
tableData.appendChild(trData)
table {
border: 1px solid #333;
border-collapse: collapse
}
table tr td, table tr th {
border: 1px solid #333;
padding: 5px;
}
<table id="tableData"></table>
Related
thanks for reading my post!
I've been trying to create a function that will take the objects in an array of employee data and display them in a table.
Within the class called 'system', I have system.giveAllEmployees(), which returns the array of all the employees, while system.giveAllOffers() returns all the active offers that have been put in the system. It should all be organized in the table employeeData, and run through and see how many offers each employee is assigned to, and add that to the table as well. It works and loads to the table but instead of updating the offer for each employee, whenever a new offer is loaded to the system it updates the offer number for all the employees in the table.
I assume this is because of how i set up the loop? but i'm really stumped as to why this is happening. I can provide any other information or code needed, if anyone knows a better way to load data from arrays into a table id appreciate that as well!
function loadAll() {
var a = system.giveAllEmployees();
var b = system.giveAllOffers();
var tr = "";
var table = document.getElementById("employeeData");
let offers = 0;
table.innerHTML = "";
a.forEach( x => {
b.forEach( y => {
if (x.employeeName === y.name) {
offers += 1;
}
return offers;
}),
tr += '<tr>';
tr += '<td>' + x.name + '</td>'
+ '<td>' + x.document + '</td>'
+ '<td>' + x.departament + '</td>'
+ '<td>' + x.age + '</td>'
+ '<td>' + offers + '</td>';
tr += '</tr>';
offers = 0;
})
table.innerHTML += tr;
}
And for context, here's a picture of the table the data is loaded into:
Thanks again for any tips or help on this issue!
I suspect a careless error:
change
if (x.employeeName === y.name) {
to
if (y.employeeName === x.name) {
full code:
for info -> https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow
function loadAll()
{
const
Employees = system.giveAllEmployees()
, Offers = system.giveAllOffers()
, tableBody = document.querySelector('#employee-table > tbody')
;
tableBody.innerHTML = '';
Employees.forEach( emp =>
{
let newRow = tableBody.insertRow()
newRow.insertCell().textContent = emp.name
newRow.insertCell().textContent = emp.document
newRow.insertCell().textContent = emp.departament
newRow.insertCell().textContent = emp.age
newRow.insertCell().textContent = Offers.filter(({employeeName:eNam})=>eNam===emp.name).length
})
}
Demo (and to show you how to do for your next questions)
function loadAll()
{
const
Employees = system.giveAllEmployees()
, Offers = system.giveAllOffers()
, tableBody = document.querySelector('#employee-table > tbody')
;
tableBody.innerHTML = '';
Employees.forEach( emp =>
{
let newRow = tableBody.insertRow()
newRow.insertCell().textContent = emp.name
newRow.insertCell().textContent = emp.document
newRow.insertCell().textContent = emp.departament
newRow.insertCell().textContent = emp.age
newRow.insertCell().textContent = Offers.filter(({employeeName: eNam})=>eNam===emp.name).length
})
}
// test datas
const system =
{
giveAllEmployees() {
return (
[ { name: 'Joseph', document: '123456', departament : 'Artgas', age: 23 }
, { name: 'Mary', document: '666222', departament : 'Artgas', age: 41 }
] ) }
, giveAllOffers() {
return (
[ { employeeName: 'Mary', xxx: 'xxx' }
, { employeeName: 'Joseph', zzz: 'zzz' }
, { employeeName: 'Mary', yyy: 'yyy' }
] ) }
};
// testing :
loadAll()
table#employee-table {
font-family : Arial, Helvetica, sans-serif;
font-size : 12px;
border-collapse : separate;
border-spacing : 1px;
background-color : darkslategrey;
}
#employee-table th,
#employee-table td {
background-color : whitesmoke;
padding : .3em .6em;
text-align : center;
}
<table id="employee-table">
<thead>
<tr>
<th>Employee Name</th> <th>Document</th> <th>Departement</th> <th>Age</th> <th>Number of Offers</th>
</tr>
</thead>
<tbody></tbody>
</table>
My HTML table
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Average</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
Sample table generation
var arrayofObjects = [{sID: 025, name: John Doe, average: 80}, {sID: 893, name: Jane Smith, average: 82}];
function loadTable() {
let table = document.getElementById("tableBody");
table.innerHTML = "";
let tr = "";
vararrayofObjects.forEach(x => {
tr += '<tr>';
tr += '<td><a data-toggle="modal" data-target="#myModal1" id="sIDNum">' + x.sID + '</a></td>' + '<td>' + x.name + '</td>' + '<td>' + x.average + '</td>';
tr += '</tr>'
})
table.innerHTML += tr;
}
What I tried to get value of first column (sID) on click then loop through object array
const tableBody = document.querySelector('#tableBody');
tableBody.addEventListener('click', (e) => {
vararrayofObjects.forEach((element) => {
if(element.sID == $('a').text()) {
var personName = element.name;
var personID = $('#sIDNum').text();
var personAvg = "Average " + element.average;
}
});
});
Problem is that the if statement returns me all values of $('a').text()) instead of the one I clicked on. How do I properly implement it so that clicking on my anchor tag on the first column (sIDNum) will get its value, then use that value to loop through my object array and get the values of the object that matches with it?
I am trying to create a table based on some input parameters "header,
body" the header receives a string "header1, header" with its values
separated by, and the body receives an array containing arrays with
strings separated by, I try to paint the body values but the values
are displayed horizontally.
This post applies to an environment where you cannot manipulate the dom "Oracle Integration Cloud"
function convertStringToHtml(headers, body) {
var headersArr = headers.split(",");
var table = "<table>";
var tableHeader = "<thead><tr>";
var tableBody = "<tbody>";
var bodyArr = [];
headersArr.forEach((headerTable) => {
tableHeader = tableHeader + "<th>" + headerTable + "</th>";
});
body.forEach((bodyTable) => {
bodyTable.forEach((List) => {
bodyArr.push(List.split(","));
});
});
var longest = bodyArr.reduce(
(headers, body) => (headers.length > body.length ? headers : body), []
);
bodyArr.forEach((bodyList, listKey) => {
tableBody = tableBody + "<tr>";
bodyList.forEach((list, key) => {
console.log(list);
if (list.length !== longest.length - 1) {
console.log(" list: ", list, " key :", key, " listKey:", listKey);
tableBody = tableBody + "<td>" + bodyArr[listKey][key] + "</td>";
}
});
tableBody = tableBody + "</tr>";
});
table =
"<table>" +
tableHeader +
"</tr></thead>" +
tableBody +
"</tbody>" +
"</table>";
return table;
}
var headerList = "Header 1,Header 2,Header 3";
var dataList = [
["TEST1,TEST1,TEST1"],
["TEST2,TEST2,TEST2"],
["TEST3,TEST3,TEST3"],
];
console.log(convertStringToHtml(headerList, dataList));
Response Expected
<table border="1">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>TEST1</td>
<td>TEST2</td>
<td>TEST3</td>
</tr>
<tr>
<td>TEST1</td>
<td>TEST2</td>
<td>TEST3</td>
</tr>
<tr>
<td>TEST1</td>
<td>TEST2</td>
<td>TEST3</td>
</tr>
</tbody>
</table>
As #Taplar said you should include a minimal reproducible example and follow the website's best practices.
That said, and generally speaking, once you have a string that contains some HTML you can insert in your page and to do that you need an DOM node.
<div id="root"></div>
Once you have created your container or you have identified the one you want to put your element into, you can do so by selecting it and working with its innerHTML attribute.
let rootElement = document.querySelector('#root')
document.innerHTML = "<table><thead><tr><th>Header 1</th><th>Header 2</th><th>Header 3</th></tr></thead><tbody><tr><td>TEST1</td><td>TEST1</td><td>TEST1</td></tr><tr><td>TEST2</td><td>TEST2</td><td>TEST2</td></tr><tr><td>TEST3</td><td>TEST3</td><td>TEST3</td></tr></tbody></table>"
You can find more info on this attribute here.
var headerList = "Header 1,Header 2,Header 3";
var dataList = [
["TEST11,TEST12,TEST13"],
["TEST21,TEST22,TEST23"],
["TEST31,TEST32,TEST33"],
];
var tableHTML=
"<table border=1>\n"+
" <thead>\n"+
" <tr>\n"+
headerList.split(",").map(header=>" <th>"+header+"</th>\n").join("")+
" </tr>\n"+
" </thead>\n"+
" <tbody>\n"+
dataList.map(row=>" <tr>\n"+
row[0].split(",").map(cell=>" <td>"+cell+"</td>\n").join("")+
" </tr>\n").join("")+
" </tbody>\n"+
"</table>";
document.body.innerHTML+=tableHTML;
console.log(tableHTML);
headerList.split(",") returns an array of headers.
Then, we map each to be surrounded with th.
Then, we join them to be the content of the row.
dataList.map takes each sub array of the body - dataList.
row[0] takes the first (and only) item of those sub arrays.
We then split for each cell content and surround with td.
Then, we join them to be the content of a row.
It's done until all rows are created.
We surround the header row with thead, and
the body rows with tbody, and
the whole thing with table.
At the end, we add tableHTML to the document.body's innerHTML -
and we're done!
Added indentation and linebreaks.
Solution:
function convertStringToHtml(headers, body) {
var headersArr = headers.split(",");
var table = "<table>";
var tableHeader = "<thead><tr>";
var tableBody = "<tbody>";
var bodyArr = [];
// Order Array Data
var orderArr = [];
var responseArr = [];
const lengthBodyElementArr = body[0][0].split(",").length;
// Create Header Table
headersArr.forEach((headerTable) => {
tableHeader = tableHeader + "<th>" + headerTable + "</th>";
});
// Order Array
for (var increment = 0; increment < lengthBodyElementArr; increment++) {
orderArr = [];
body.forEach((bodyElement) => {
bodyElement.forEach((internalBodyElement) => {
bodyArr = internalBodyElement.split(",");
bodyArr.forEach((element, key) => {
if (key == increment) {
orderArr.push(element);
}
});
});
});
responseArr.push(orderArr);
}
// Create Body Table
responseArr.forEach((bodyList) => {
tableBody = tableBody + "<tr>";
bodyList.forEach((element) => {
tableBody = tableBody + "<td>" + element + "</td>";
});
tableBody = tableBody + "</tr>";
});
table =
"<table>" +
tableHeader +
"</tr></thead>" +
tableBody +
"</tbody>" +
"</table>";
return table;
}
I'm looping an object and expect the result as elements of a table
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
},
pp_ = '<table><tbody>';
for (var i in db) {
if (db.hasOwnProperty(i)) {
var js = db[i].split(',');
for (var x in js) {
if (i.startsWith('pp_')) {
pp_ += '<tr><td>' + i + ' ' + x + ' : ' + js[x] + '</td></tr>';
}
}
}
}
pp_ += '</tbody></table>';
document.write(pp_);
I am splitting values that have commas so that each index of an array sits on 1 row (tr)
what I can't figure out is how to place elements with the same index on the same level (row) so I can I have something like
table, td {
border: 1px solid black;
}
<table>
<tbody>
<tr>
<td> pp_flavour 0 - its value </td>
<td> pp_fruit_batch 0 - its value </td>
</tr>
<tr>
<td> pp_flavour 1 - its value </td>
<td> pp_fruit_batch 1 - its value </td>
</tr>
<tr>
<td> pp_flavour 2 - its value </td>
<td> pp_fruit_batch 2 - its value </td>
</tr>
</tbody>
</table>
<br>
<table>
<tbody>
<tr>
<td> sl_favour 0 - its value </td>
<td> sl_appearance 0 - its value </td>
</tr>
<tr>
<td> sl_favour 1 - its value </td>
<td> sl_appearance 1 - its value </td>
</tr>
</tbody>
</table>
and so on...
You could try indexing the database like this:
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
};
var prefixes = ["pp", "ht", "sl"];
var prefixedDb = {};
var result = "";
for (var i in db) {
if (db.hasOwnProperty(i)) {
var parts = i.split("_");
var prefix = parts[0];
if (prefixes.indexOf(prefix) === -1) continue;
if (prefixedDb[prefix] === undefined) {
prefixedDb[prefix] = {};
}
prefixedDb[prefix][parts.slice(1).join("_")] = db[i];
}
}
for (var k in prefixedDb) {
if (prefixedDb.hasOwnProperty(k)) {
var db = prefixedDb[k];
var dbIndexed = {};
for (var i in db) {
if (db.hasOwnProperty(i)) {
var vals = db[i].split(',');
vals.forEach(function(val, j) {
if (dbIndexed[j] === undefined) {
dbIndexed[j] = {};
}
dbIndexed[j][i] = val;
});
}
}
result += "<table><tbody>";
for (var i in dbIndexed) {
if (dbIndexed.hasOwnProperty(i)) {
result += "<tr>";
var indexVals = dbIndexed[i];
for (var j in indexVals) {
if (indexVals.hasOwnProperty(j)) {
result += "<td>" + j + " " + i + " - " + indexVals[j] + "</td>";
}
}
result += "</tr>";
}
}
result += "</tbody></table>";
}
}
document.write(result);
table, td {
border: 1px solid black;
}
Please note that this code may not be the most optimized code for this task.
You can try adding each value of the table to a 2-D array and than form the table from this 2-D array
try below solution
NOTE: this will also work with different number of rows and Column.
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
};
function createTable(myKey){
var rows = [];
for (var dbKey in db) {
if (db.hasOwnProperty(dbKey)) {
if (dbKey.startsWith(myKey)) {
var values = db[dbKey].split(',');
for (var val in values) {
if (!rows[val])
rows[val] = [];
rows[val].push('<td>' + dbKey + ' ' + val + ' : ' + values[val] + '</td>');
}
}
}
}
var myTable = '<table><tbody>';
for (var i = 0; i < rows.length; i++) {
myTable += "<tr>" + rows[i].join("") + "</tr>";
}
myTable += '</tbody></table>';
return myTable;
}
var ht_table = createTable("ht_");
document.getElementById("myTable").innerHTML +="<br/>"+ ht_table;
var pp_table = createTable("pp_");
document.getElementById("myTable").innerHTML +="<br/>"+ pp_table;
var sl_table = createTable("sl_");
document.getElementById("myTable").innerHTML += "<br/>"+ sl_table;
table, td {
border-style: solid;
}
<p id="myTable">
</p>
You could take the wanted values out of the object, split them and take the max length for iterating the rows for the table. Then assemble the table by iterating the values.
var db = { pp_flavour: "ytv,yurtcrc,urt", pp_fruit_batch: "cuyt,cytc,yt,42" },
values = Object.keys(db).filter(k => k.startsWith('pp_')).map(k => (db[k] || '').split(',')),
length = values.reduce((r, a) => Math.max(r, a.length), 0),
table = document.createElement('table'),
tr,
i;
for (i = 0; i < length; i++) {
tr = document.createElement('tr');
table.appendChild(tr);
values.forEach(function (a) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(i in a ? a[i] : ''));
tr.appendChild(td);
});
}
document.body.appendChild(table);
Create a loop, incrementing a counter, which will determine if a key's split value should be output.
If there are no more values found at the index of the counter, stop looping.
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
},
s = '';
['pp_', 'ht_', 'sl_'].forEach(function(type) {
var i,
found = true;
s += '<table>';
for(i = 0 ; found ; i++) {
s += '<tr>';
found = false;
Object.keys(db).forEach(function(key) {
var js = db[key].split(',');
if(js[i] && key.startsWith(type)) {
found = true;
s += '<td>' + key + ' ' + i + ' : ' + js[i] + '</td>';
}
});
s += '</tr>';
}
s += '</table>';
});
document.write(s);
td {
border-bottom: 1px solid #bbb;
border-right: 1px solid #ddd;
padding: 0.5em;
}
table {
border: 1px solid black;
margin-bottom: 1em;
border-spacing: 0;
}
I want to create HTML table in java script. Inside a for loop I want to create a dynamic table which can be extended. This is how I am it using now:
function(json)
{
var content= $('#name1').html('').append('<td> Name: ' + json.name + '<td>');
var content= $('#address1').html('').append('<td> address: ' + json.address + '<td>');
var content= $('#age1').html('').append('<td> age: ' + json.age + '<td>');
var content= $('#status1').html('').append('<td> status: ' + json.status + '<td>');
}
HTML file is
<table>
<tr id="name1"></tr>
<tr id="address1"></tr>
<tr id="age1"></tr>
<tr id="status1"></tr>
</table>
now it is just with hardcore values but I want it auto generated and insert more rows if neccessary...
remove id from tr. Because if you need multiple row then id will be duplicated which is not valid.
<table id="mytable">
</table>
function(json)
{
for(i=0;i<json.length;i++){
var newRow= $("<tr></tr>");
newRow.append('<td> Name: ' + json[i].name + '<td>');
newRow.append('<td> address: ' + json[i].address + '<td>');
newRow.append('<td> age: ' + json[i].age + '<td>');
newRow.append('<td> status: ' + json[i].status + '<td>');
$("#mytable").append(newRow);
}
}
i think this will help you
function(json)
{
for(i=0;i<jsn.length;i++){
$('#YOUR_TABLE_ID').append("<tr><td>"+ json.name+"</td></tr>")
}
}
<table id="mytable">
<tr id="name1"><td></td></tr>
</table>
if (results != null && results.length > 0) {
// Build our table header
var content = "";
for(i=0;i<data.length;i++)
{
content += '<tr>';
content += '<td></td>'
}
content += '</tr>';
}
$("#mytable tbody").append(content);
}
You can Use Append Method to create Rows in a table like
for(i=0;i<data.length;i++)
{
$("YOUR_TABLE_ID").append("<tr><td>"+data[i]['name']+"</td><td>"+data[i]['address']+"</td><td>"+data[i]['age']+"</td><td>"+data[i]['status']+"</td></tr>");
}
I'm not clear with your requirement but i can provide you some basic code hope that helps you.
var jsonList = [{name:'Jhon',address:'Jhon Address goes here',age:'27',status:'Single'},
{name:'Smith',address:'Smith Address goes here' ,age:'32', status:'Single' }];
function createTable(){
var table = '<table>';
for(var ind=0;ind< jsonList.length;ind++)
table += fetchRowInformation(jsonList[ind]);
console.log(table+'</table>');
}
function fetchRowInformation(json){
return '<tr><td> Name: ' + json.name + '<td>'+'<td> address: ' + json.address + '<td>'+ '<td> age: ' + json.age + '<td>'+'<td> status: ' + json.status + '<td></tr>';
}
JS Fiddle Demo
function tableCreate(rows, columns) {
var body = document.body
tbl = document.createElement('table');
tbl.style.width = '20%';
tbl.style.border = '1px solid black';
for (var i = 0; i < rows; i++) {
var tr = tbl.insertRow();
for (var j = 0; j < columns; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode('Cell'));
td.style.border = '1px solid black';
}
}
tbl.style.marginTop = '10px'
tbl.style.borderCollapse = 'collapse'
td.style.padding = '2px'
body.appendChild(tbl);
}
tableCreate(15, 10);