The task is to fill the table with data from arrays id, name and price.
What am I doing wrong?
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
It doesn't work, because your input data is not organised as an array of objects, but as an object of arrays (which is less OOP).
As I prefer the array of objects as data structure, I would suggest to (temporarily) convert to that structure, and then your loop will work as expected:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(array, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
As an unrelated remark, I would suggest using jQuery more in the process of building the table. This will also avoid problems you might get when your data has < or & characters in it immediately followed by letters, as that would be interpreted as HTML:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
$('#tableContainer').empty().append($("<table>").addClass("mainTable").append(
$("<tr>").append(
$("<th>").text("id"),
$("<th>").text("name"),
$("<th>").text("price")
),
...array.map(value =>
$("<tr>").append(
$("<td>").text(value.id),
$("<td>").append($("<img>", { src: value.name })),
$("<td>").text(value.price)
)
)
));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
Your data structure is not iterable. So you need to either change your data structure to be a list [{id: '1111', name: 'name1', price: 1111}], or you need to assume that all lists (id, name, price) are the same length, and use that length for the iteration.
As other answers detail how to use an iterable data structure, I'll handle the other method, where your data is already in this format, and won't change.
For this method, find the length of one property (id, name or price), and iterate through all of them using the index. Here is an example.
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
data.id.forEach((value, index) => {
table += ('<tr>');
table += ('<td>' + data.id[index] + '</td>');
table += ('<td><img src="' + data.name[index] + '"></td>');
table += ('<td>' + data.price[index] + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
You're processing the data as if it were structured as a single array, like this:
data = [
{
id: 1986,
name: "name1",
price: 1148
}
]
However, your data contains three arrays, not one:
data = {
id: [...],
name: [...],
price: [...],
}
If the data was structured like the first example, then value would contain an object for each array element, with the properties id, name and price available.
An option is to convert the first data structure to the second:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
id: id,
name: data.name[index],
price: data.price[index]
}))
Then, use the mappedData and access the properties as you're already doing, as follows:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
id: id,
name: data.name[index],
price: data.price[index]
}))
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(dataMapped, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data["id"], function(index, value){
table += ('<tr>');
table += ('<td>' + value + '</td>');
table += ('<td><img src="' + data["name"][index] + '"></td>');
table += ('<td>' + data["price"][index] + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
There ways to iterate the data as you defined it but I think it's better to define it in a proper way, as an array of entities ($.each is to iterate through an array):
[
{
"id": "1986",
"name": "name1",
"price": 1148
},
{
"id": "1990",
"name": "name2",
"price": 1396
},
];
Without changing the input you can do this.
var data = {
"id": ["1986", "1990", "1989", "1985", "1988", "1987"],
"name": ["name1", "name2 ", "name3 ", "name4", "латунь матовая ", "name5"],
"price": [1148, 1396, 2775, 1270, 1396, 1270]
};
document.getElementById("tableContainer").innerHTML = data.id
.map((id,i) => `<tr><td>${id}</td>
<td><img src="${data.name[i]}"></td>
<td>${data.price[i]}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table class="mainTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody id="tableContainer"></tbody>
</table>
</div>
I also recommmend you change the input to an array of objects. It makes the parsing simpler
var data = [
{ "id": "1986", "name": "name1", "price": 1148},
{ "id":"1990", "name": "name2", "price": 1396},
{ "id":"1989", "name": "name3", "price": 2775},
{ "id":"1985", "name": "name4", "price": 1270},
{ "id":"1988", "name": "латунь матовая ", "price": 1396},
{ "id":"1987", "name": "name5", "price": 1270}
];
document.getElementById("tableContainer").innerHTML = data
.map(({id,name,price}) => `<tr><td>${id}</td>
<td><img src="${name}"></td>
<td>${price}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table class="mainTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody id="tableContainer"></tbody>
</table>
</div>
I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>
Through that jQ bootstrap 4 datatable grid (datatable.net) I want for tabular display the following xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persns>
<prsn>
<fname>Smith</fname> <!-- first name-->
<lname>Milton</lname> <!-- last name -->
<age>44</age>
<e-mail>smilt#gmail.com</e-mail>
<phnmbr>3568236712</phnmbr>
<addrss>5th summer st, mntb</addrss>
<city>Portland</city>
</prsn>
<prsn>
<fname>Ken</fname>
<lname>Jackson</lname>
<age>37</age>
<e-mail>ken.jackson#yahoo.com</e-mail>
<phnmbr>2638762076</phnmbr>
<addrss>19th Penfield ave, brtcl</addrss>
<city>Kelowna</city>
</prsn>
<prsn>
<fname>Susan</fname>
<lname>Arkland</lname>
<age>48</age>
<e-mail>s.arklnd#hotmail.com</e-mail>
<phnmbr>50834219704</phnmbr>
<addrss>34th Mansfield st, sgtp</addrss>
<city>Raleigh</city>
</prsn>
<prsn>
<fname>Patsy</fname>
<lname>Brighton</lname>
<age>38</age>
<e-mail>patsy.brghton#gmail.com</e-mail>
<phnmbr>814522096358</phnmbr>
<addrss>12th Peel st, pnslv</addrss>
<city>Philadelphia</city>
</prsn>
<prsn>
<fname>John</fname>
<lname>Torg</lname>
<age>54</age>
<e-mail>john.torg#tzeus.com</e-mail>
<phnmbr>042197327784</phnmbr>
<addrss>27th north st, cnda</addrss>
<city>Penticton</city>
</prsn>
but with master-detail functionality as it is shown over the following fiddle link:
https://jsfiddle.net/nnb97rh9/3/
Only that up to that fiddle there is .json data ! (and I need for .xml display)
The corresponding (almost functional) .js (through the master table I only want to display the following table headers:
fname, lname, age, city while the rest would be hidden; they'll only be displayed as related child table lines) is as follows:
$(function(){
var prstbl = $("#prsns").dataTable(columns: [{"class":'details-control',
"orderable":false, "data":null, "defaultContent":''},
{dtaTbl:"fname"},
{dtaTbl:"lname"},
{dtaTbl:"age"},
{dtaTbl:"city"},
{dtaTbl:"e-mail", "visible":false},
{dtaTbl:"phnmbr", "visible":false},
{dtaTbl:"addrss", "visible":false}
]}),
oTable = $('#prsne').DataTable()
function format(d)
{
return '<table cellpadding="3" cellspacing="0" border="0" style="padding-
left:40px">'
+ '<tr>' + '<td>e-mail addrss</td>'
+ '<td>' + d.email + '</td>' + '</tr>'
+ '<tr>' + '<td>phn nmber</td>'
+ '<td>' + d.phnmbr + '</td>' + '</tr>'
+ '<tr>' + '<td>address</td>'
+ '<td>' + d.addrss + '</td>' + '</tr>'
+ '</table>'
}
$.ajax({type:"GET", url:"persns.xml", dataType:"xml", success:
function(xml)
{
var prsns = $(xml).find("prsn")
prsns.each(function(idx, prs)
{
var prs = $(prs), dtaTbl = []
prs.children().each(function(j,chdnd)
{
dtaTbl.push($(chdnd).text())
})
prstbl.fnAddData(dtaTbl)
})
}
})
$('#prsns tbody').on('click', 'td.details-control', function()
{
var tr = $(this).closest('tr'),
row = oTable.row(tr)
if(row.child.isShown()) // if the row is already expanded,
collapse it
{
row.child.hide()
tr.removeClass('shown')
}
else // if collapsed row, expandit it
{
row.child(format(row.data())).show()
tr.addClass('shown')
}
})
})
The relevant .html part is like this:
<body>
<h5>Master-detail persons display</h5>
<table id="prsns" border="1" class="table display" width="60%">
<thead><tr><th></th><th>frst nme</th><th>name</th><th>age</th>
<th>city</th> <th>e-mail addrss</th></tr></thead>
<tbody></tbody>
</table>
</body>
And there is also a small .css file like this:
td.details-control
{
background:url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control
{ background:url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_close.png') no-repeat center center;
}
I repeat, all the displaying I need to be done regarding this .xml file and not .json or only .html !
I know how to do it with .json table.
So you guys please help me with this issue.
Thank you all in advance
There are multiple issues with the code, too much to describe. Below is the corrected code.
Please note I am using jsFiddle mechanism to retrieve XML file, replace with your own.
(function () {
function format(d) {
return '<table cellpadding="3" cellspacing="0" border="0" style="padding-left: 40 px ">' +
'<tr>' + '<td>e-mail addrss</td>' +
'<td>' + d['e-mail'] + '</td>' + '</tr>' +
'<tr>' + '<td>phn nmber</td>' +
'<td>' + d['phnmbr'] + '</td>' + '</tr>' +
'<tr>' + '<td>address</td>' +
'<td>' + d['addrss'] + '</td>' + '</tr>' +
'</table>';
}
var prstbl = $("#prsns").DataTable({
columns: [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{
data: "fname"
},
{
data: "lname"
},
{
data: "age"
},
{
data: "city"
},
{
data: "e-mail",
"visible": false
},
{
data: "phnmbr",
"visible": false
},
{
data: "addrss",
"visible": false
}
]
});
$.ajax({
type: "POST",
url: "/echo/xml",
data: {
xml: '<?xml version="1.0" encoding="UTF-8" ?><persns>'
+ '<prsn><fname>Smith</fname><lname>Milton</lname><age>44</age><e-mail>smilt#gmail.com</e-mail><phnmbr>3568236712</phnmbr><addrss>5th summer st, mntb</addrss><city>Portland</city></prsn>'
+ '<prsn><fname>Ken</fname><lname>Jackson</lname><age>37</age><e-mail>ken.jackson#yahoo.com</e-mail><phnmbr>2638762076</phnmbr><addrss>19th Penfield ave, brtcl</addrss><city>Kelowna</city></prsn>'
+ '<prsn><fname>Susan</fname><lname>Arkland</lname><age>48</age><e-mail>s.arklnd#hotmail.com</e-mail><phnmbr>50834219704</phnmbr><addrss>34th Mansfield st, sgtp</addrss><city>Raleigh</city></prsn>'
+ '<prsn><fname>Patsy</fname><lname>Brighton</lname><age>38</age><e-mail>patsy.brghton#gmail.com</e-mail><phnmbr>814522096358</phnmbr><addrss>12th Peel st, pnslv</addrss><city>Philadelphia</city></prsn>'
+ '<prsn><fname>John</fname><lname>Torg</lname><age>54</age><e-mail>john.torg#tzeus.com</e-mail><phnmbr>042197327784</phnmbr><addrss>27th north st, cnda</addrss><city>Penticton</city></prsn>'
+ '</persns>',
},
dataType: 'xml',
success: function (xml) {
var prsns = $(xml).find("prsn");
prsns.each(function (idx, prs) {
var rowData = [];
$(prs).children().each(function (j, chdnd) {
rowData[$(chdnd).get(0).tagName] = $(chdnd).text();
});
prstbl.row.add(rowData);
});
prstbl.draw();
}
});
$('#prsns tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = prstbl.row(tr);
// if the row is already expanded, collapse it
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
// if collapsed row, expand it
} else {
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
})();
See updated example for code and demonstration.
I have nested array json object (Layer 1, Layer 2 and Layer 3). My problem is dataTables does not appear. Any related CDN has been imported. The table just only display <thead> section. I have referred many websites, but it did not solve my problem.
Earlier I was using standard table to display the values inside Layer 3 json using <tbody>, <tr> and <td>, do the result is successful. But now I removed all that and try to use dataTable as I need its' features.
I successfully displayed value id for Layer 1 and Layer 2. But for my case below, it is unsuccessfully to display Layer 3 information (l3_id, l3_name, etc..) in dataTables.
JSON
{
"status": "Success",
"data": [{
"project_id": "1",
"project_name": "project name",
"l1_task": [{
"l1_id": "1",
"l1_name": "Layer 1",
"l2_task": [{
"l2_id": "1",
"l2_name": "Layer 2",
"l3_task": [{
"l3_id": "1",
"l3_name": "Layer 3.1"
},
{
"l3_id": "2",
"l3_name": "Layer 3.2"
}
]
}]
}]
}]
}
JS
$(document).ready(function() {
loadtable();
$('#Layer3Table').DataTable({
ajax: {
url: "exampleData/activity.json"
},
columns: [{
data: "l1_task.0.l2_task.0.l3_task.0.l3_id"
},
{
data: "l1_task.0.l2_task.0.l3_task.0.l3_name"
}
],
});
function loadtable() {
var project = '';
$.ajax({
url: url_project_detail,
crossDomain: true,
type: 'POST',
dataType: 'json',
data: "data",
success: function(response) {
if (response.status == "Success") {
// Layer 1 array object
$.each(response.data[0].l1_task, function(key, value) {
project +=
"<div>" +
"<div>";
// Layer 2 array object
$.each(value.l2_task, function(key, value) {
project +=
"<div>" +
"<div>" +
// Layer 3 array object
"<div class='table-responsive'>" +
"<table id='Layer3Table' class='table table-striped' style='width:100%'>" +
"<thead>" +
"<tr>" +
"<th class='text-center'>ID</th>" +
"<th class='text-center'>Activity Name</th>" +
"</tr>" +
"</thead>" +
"</table>" +
"</div>";
}); // for Layer 2
project += "</div>" + "</div>";
}); // for Layer 1
$("#projectDetail2").append(project);
} else {}
},
error: function(e) {}
});
}
});
I just got the solution by removing this dataTables.
$('#Layer3Table').DataTable({
ajax: {
url: "exampleData/activity.json"
},
columns: [{
data: "l1_task.0.l2_task.0.l3_task.0.l3_id"
},
{
data: "l1_task.0.l2_task.0.l3_task.0.l3_name"
}
],
});
and initiate dataTables at this section
}); // for Layer 1
$("#projectDetail2").append(project);
$('#Layer3Table').DataTable();
} else {}
UPDATE
Nice job on figuring this one out on your own, OP. I will include the solution in my answer as well.
You were appending the table after calling datatables so it makes sense you would need to put the call to datatables after appending the table with the data in it. I should have caught that, nice job!
Your success function does not loop through l3_task. Try this ..
success: function(response) {
if (response.status == "Success") {
// Layer 1 array object
$.each(response.data[0].l1_task, function(key, value) {
project +=
"<div>" +
"<div>";
// Layer 2 array object
$.each(value.l2_task, function(key1, value1) {
project +=
"<div>" +
"<div>" +
// Layer 3 array object
"<div class='table-responsive'>" +
"<table id='Layer3Table' class='table table-striped' style='width:100%'>" +
"<thead>" +
"<tr>" +
"<th class='text-center'>ID</th>" +
"<th class='text-center'>Activity Name</th>" +
"</tr>" +
"</thead>";
$.each(value1.l3_task, function(k, v) {
project +=
"<tr>" +
"<td>" + v.l3_id + "</td>" +
"<td>" + v.l3_name + "</td>" +
"</tr>";
});
project +=
"</table>" +
"</div>";
}); // for Layer 2
project += "</div></div></div></div>";
}); // for Layer 1
$("#projectDetail2").append(project);
$('#Layer3Table').DataTable();
} else {}
},
I have some code that grabs a JSON objects and displays it in a HTML table, however the table is not displaying correctly.
I want the table to be displayed like this:
_________________
| Product1 |
==================
| 1852ak | 2016 |
==================
| refurbished |
__________________
Here is my code:
var product = {
"name": "Product1",
"model": "1852ak",
"year": "2016",
"details": "refurbished"
}
$(document).ready(function() {
var row = $('<tr>');
row.append('<tr><td colspan = 2s>' + product.name + '</td></tr>');
row.append('<tr><td>' + product.model + '</td></tr>');
row.append('<td>' + product.year + '</td></tr>');
row.append('<tr><td>' + product.details + '</td></tr>');
$('#sample').append(row);
});
Any help would be greatly appreciated!
The problem is that you're adding rows to your existing rows.
In addition to this, you are considering the table to be one singular 'object', and are adding both the rows and the cells directly to the table. The table cells should be added to their containing rows.
What I would recommend doing is defining three separate rows as independent variables, then adding the cells to their respective rows. As the row has all of its content created, it gets added to the table:
var product = {
"name": "Product1",
"model": "1852ak",
"year": "2016",
"details": "refurbished"
}
$(document).ready(function() {
var table = $('#sample');
var row1 = $('<tr>');
var row2 = $('<tr>');
var row3 = $('<tr>');
row1.append('<td colspan = 2>' + product.name + '</td>');
table.append(row1);
row2.append('<td>' + product.model + '</td>');
row2.append('<td>' + product.year + '</td>');
table.append(row2);
row3.append('<td colspan = 2>' + product.details + '</td>');
table.append(row3);
});
td {
border: 1px solid black;
text-align: center;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sample"></table>
Hope this helps! :)
Try this Code:
var product =
{
"name":"Product1",
"model":"1852ak",
"year":"2016",
"details":"refurbished"
}
$(document).ready(function()
{
var row =$('table');
row.append ('<tr><td colspan = "2">' + product.name + '</td></tr>');
row.append('<tr><td>' + product.model + '</td><td>' + product.year + '</td></tr>');
row.append ('<tr><td colspan = "2">' + product.details + '</td></tr></table>');
$('#sample').append(row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample"></div>
Presuming that $("#sample") is your table