Parsing JSON objects to HTML table - javascript

I'm trying to parse a JSON object into an html table however I can't seem to get it right.
DESIRED FORMAT:
Last Year This Year Future Years
45423 36721 873409
CURRENT FORMAT:
Last Year 45423
This Year 36721
Future Years 873409
JSON:
[{column_name:"Last Year", "column_data":45423},{column_name:"This Year", "column_data":36721},{column_name:"Future Years", "column_data":873409}]
HTML:
<div class="panel-body">
<div id="main-aged-debtors-bar" style="height: 250px"></div>
<div>
<table class="table table-hover" id="crpw_table">
<thead>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
CODE:
$.getJSON(url, jsonObject,
function (data) {
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].column_name + "</td>");
tr.append("<td>" + data[i].column_data + "</td>");
$('#crpw_table').append(tr);
}
});

It's not much different
$.getJSON(url, jsonObject,
function (data) {
tr1 = $('<tr/>');
tr2 = $('<tr/>');
for (var i = 0; i < data.length; i++) {
tr1.append("<td>" + data[i].column_name + "</td>");
tr2.append("<td>" + data[i].column_data + "</td>");
}
$('#crpw_table').append(tr1);
$('#crpw_table').append(tr2);
}
);

$.getJSON(url, jsonObject,
function (data) {
var tr = $('<tr/>');
for (var i = 0; i < data.length; i++) {
tr.append("<td>" + data[i].column_name + "</td>");
}
$('#crpw_table').append(tr);
tr = $('<tr/>');
for (i = 0; i < data.length; i++) {
tr.append("<td>" + data[i].column_data + "</td>");
}
$('#crpw_table').append(tr);
});

Try,
$.getJSON(url, jsonObject,
function (data) {
var tr1 = $('<tr/>');
var tr2 = $('<tr/>');
for (var i = 0; i < data.length; i++) {
tr1.append("<td>" + data[i].column_name + "</td>");
tr2.append("<td>" + data[i].column_data + "</td>");
}
$('#crpw_table').append(tr1).append(tr2);
});

Related

How to add dynamic radio button to dynamic created table in jquery

I want to add the radio button to the dynamically created table.
This is the HTML code where I am adding the dynamically created object.
<div class="row container">
<div class=" col m12 l6 s12" style="height:200px; overflow:scroll;">
<table id="staff">
</table>
</div>
<div class=" col m12 l6 s12" style="height:200px; overflow:scroll;">
<table id="patient">
</table>
</div>
</div>
Here is the Jquery Code for the website
$.ajax({
type: "POST",
url: "/public/src/management/serverfile/selectstaffandpat.php",
dataType: "text",
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
success: function (JSONObject) {
var peopleHTML = "";
var tempjsonval = JSON.parse(JSONObject);
var str1 = "<tr><th colspan=\"4\">Staff</th></tr><tr><th>Select</th><th>ID</th><th>FirstName</th><th>LastName</th></tr>";
var count_staff = tempjsonval.staff.length;
var count_patient = tempjsonval.patient.length;
for (i = 0; i < count_staff; i++) {
str1 += "<tr><td><input type=\"radio\" name=\"staff\" value=\"" +
tempjsonval.staff[i].s_id +
"staff\" ></input></td><td>" +
tempjsonval.staff[i].s_id +
"</td><td>" +
tempjsonval.staff[i].firstname +
"</td><td>" +
tempjsonval.staff[i].lastname +
"</td></tr>"
}
document.getElementById("staff").innerHTML = str1;
str1 = "";
str1 = " <tr><th colspan=\"3\">Patient</th></tr><tr><th>ID</th><th>FirstName</th><th>LastName</th></tr>";
for (i = 0; i < count_patient; i++) {
str1 += "<tr><td>" +
tempjsonval.patient[i].p_id +
"</td><td>" +
tempjsonval.patient[i].firstname +
"</td><td>" +
tempjsonval.patient[i].lastname +
"</td></tr>"
}
document.getElementById("patient").innerHTML = str1;
}
});
});
There is input created but the radio button is not shown. Can anyone please provide a way to add a radio button with dynamic value.
this is the image where I am getting this output
Please check this one needs to changes some JSON data to ajax response data.
For testing check working demo Click here
HTML content
<div class="row container">
<div class=" col m12 l6 s12" style="height:200px; overflow:scroll;">
<table id="staff">
</table>
</div>
<div class=" col m12 l6 s12" style="height:200px; overflow:scroll;">
<table id="patient">
</table>
</div>
</div>
Javascript Code
var JSONObject = '{"staff":[{"s_id":1,"firstname":"A","lastname":"B"},{"s_id":1,"firstname":"A","lastname":"B"}],"patient":[{"p_id":1,"firstname":"A","lastname":"B"},{"p_id":1,"firstname":"A","lastname":"B"}]}';
var peopleHTML = "";
var tempjsonval = JSON.parse(JSONObject);
console.log(tempjsonval);
var str1 = "<tr><th colspan=\"4\">Staff</th></tr><tr><th>Select</th><th>ID</th><th>FirstName</th><th>LastName</th></tr>";
var count_staff = tempjsonval.staff.length;
var count_patient = tempjsonval.patient.length;
for (i = 0; i < count_staff; i++) {
str1 += "<tr><td><input type=\"radio\" name=\"staff["+i+"]\" value=\"" +
tempjsonval.staff[i].s_id +
"staff\" ></input></td><td>" +
tempjsonval.staff[i].s_id +
"</td><td>" +
tempjsonval.staff[i].firstname +
"</td><td>" +
tempjsonval.staff[i].lastname +
"</td></tr>"
}
document.getElementById("staff").innerHTML = str1;
str1 = "";
str1 = " <tr><th colspan=\"3\">Patient</th></tr><tr><th>ID</th><th>FirstName</th><th>LastName</th></tr>";
for (i = 0; i < count_patient; i++) {
str1 += "<tr><td><input type=\"radio\" name=\"patient["+i+"]\" value=\"" + tempjsonval.patient[i].p_id + "patient\" ></input></td><td>" +
tempjsonval.patient[i].firstname +
"</td><td>" +
tempjsonval.patient[i].lastname +
"</td></tr>"
}
document.getElementById("patient").innerHTML = str1;
OutPut
Note: you need to prepared radio button unique or dynamic either prepared array variable.
$.ajax({
type: "POST",
url: "/public/src/management/serverfile/selectstaffandpat.php",
dataType: "text",
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
success: function (JSONObject) {
var peopleHTML = "";
var tempjsonval = JSON.parse(JSONObject);
var str1 = `<tr><th colspan="4">Staff</th></tr>
<tr>
<th>Select</th>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>`;
var count_staff = tempjsonval.staff.length;
var count_patient = tempjsonval.patient.length;
for (i = 0; i < count_staff; i++) {
str1 +=`<tr>
<td><input type="radio" name="staff" value="${tempjsonval.staff[i].s_id} staff /></td>
<td>${tempjsonval.staff[i].s_id}</td><td>
${tempjsonval.staff[i].firstname}</td>
<td>${tempjsonval.staff[i].lastname}</td></tr>`}
document.getElementById("staff").innerHTML = str1;
str1 = "";
str1 = `<tr>
<th colspan="3">Patient</th>
</tr>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>`;
for (i = 0; i < count_patient; i++) {
str1 +=`<tr>
<td>${tempjsonval.patient[i].p_id}</td>
<td>${tempjsonval.patient[i].firstname}</td>
<td>${tempjsonval.patient[i].lastname}</td>
</tr>`
}
document.getElementById("patient").innerHTML = str1;
}
});
try to use template literal it's a nice feature

jQuery applying a function on each row of a table

I have an array of objects. I have to apply a function to each row and Log the corresponding name and id.
Here is my code:
var json = [
{
id: 1,
name: "Jon",
age: 20
},
{
id: 2,
name: "Jessy",
age: 25
},
{
id: 3,
name: "Sarah",
age: 30
},
]
console.log(json)
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].id + "</td>");
tr.append("<td>" + json[i].name + "</td>");
tr.append("<td>" + "<button class='btn btn-info'>Log</button>" + "</td>");
$('table').append(tr);
}
Using jQuery how can I apply the function and Log the id and name?
on click of a button i need to log the id and name. Each button will log their cell's name and id
so if the button in first row clicked , it should log id: 1 , name: jon
You can simply do:
var json = [{id:1,name:"Jon",age:20}, {id:2,name:"Jessy",age:25}, {id:3,name:"Sarah",age:30}];
//console.log(json)
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].id + "</td>");
tr.append("<td>" + json[i].name + "</td>");
tr.append("<td>" + "<button class='btn btn-info'>Log</button>" + "</td>");
$('table').append(tr);
}
// Attach a delegated event handler
$('table').on('click', '.btn-info', function(event) {
console.log('ID: ' + $(this).closest('tr').find('td:eq(0)').text());
console.log('Name: ' + $(this).closest('tr').find('td:eq(1)').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
You can use forEach method to loop your array and then create each row with td and button and add click event to button.
const json = [{"id":1,"name":"Jon","age":20},{"id":2,"name":"Jessy","age":25},{"id":3,"name":"Sarah","age":30}]
const tbody = $("table tbody");
json.forEach(function(obj) {
let { id, name} = obj;
let btn = $('<button>', {"class": 'btn btn-info'})
.text('Log')
.click(function() {
console.log('ID: ' + id, 'Name: ' + name)
})
let tr = $("<tr>")
.append($('<td>').text(id))
.append($('<td>').text(name))
.append($('<td>').html(btn))
tbody.append(tr)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>

How to merge cells with equal values

I have this Table where I need to merge cells with same value for a column Week.
Below is the Table I am getting as an output right now:
Week Project OS TotalTests #cycle of run
1 P1 ABC 0 0
1 P2 XYZ 4799 1
I want the output to be like ( 1 should be placed at the center of a cell) :
Week Project OS TotalTests #cycle of run
1 P1 ABC 0 0
P2 XYZ 4799 1
Here is the code:
function BindTable(startWW, endWW, selPhaseNumber, selctedYear) {
var url = webApiUrl + .....
$('#GraphTable > tbody > tr ').remove();
$.ajax({
url:url,
type: "Get",
dataType: "json",
data: { .... },
crossDomain: true,
success: function (data) {
if (data.length > 0) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].WW + "</td>");
tr.append("<td>" + data[i].Project + "</td>");
tr.append("<td>" + data[i].OS + "</td>");
tr.append("<td>" + data[i].TotalTests + "</td>");
tr.append("<td>" + data[i].CycleRun + "</td>");
$('#GraphTable').append(tr);
}
}
else {
tr = $('<tr/>');
tr.append("<th colspan='10' style='text-align:center'>No Data to display</th>");
$('#GraphTable').append(tr);
}
}
});
}
Any help ?
You can combine cells with the rowspan attribute. The Problem: If you loop through the data from the beginning, you don't know the right value for the rowspan-attribute, because ithas to be placed in the first td-element!
Solution: Loop through it from the end to the beginning:
function success(data) {
if (data.length > 0) {
var oldValue = data[data.length-1].WW,
c=1;
for (var i = data.length-1; i >= 0; i--) {
let $tr = $('<tr/>');
if(i==0 || oldValue != data[i-1].WW) {
$tr.append("<td rowspan=\""+c+"\">" + data[i].WW + "</td>");
c = 1;
if(i>0) oldValue = data[i-1].WW;
} else {
c++;
}
$tr.append("<td>" + data[i].Project + "</td>");
$tr.append("<td>" + data[i].OS + "</td>");
$tr.append("<td>" + data[i].TotalTests + "</td>");
$tr.append("<td>" + data[i].CycleRun + "</td>");
$('#GraphTable').prepend($tr);
}
} else {
let $tr = $('<tr/>');
$tr.append("<th colspan='5' style='text-align:center'>No Data to display</th>");
$('#GraphTable').append($tr);
}
}
working fiddle
EDIT: working fiddle with head-line
changed the loop order and naming convention.
If you track the last DataWW you could print it or not. You only need to print when last DataWW is different from current DataWW. You can adjust your for loop like this:
var tr;
var lastDataWW = null
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
if (lastDataWW != data[i].WW) {
tr.append("<td>" + data[i].WW + "</td>");
else {
tr.append("<td> </td>");
}
tr.append("<td>" + data[i].Project + "</td>");
tr.append("<td>" + data[i].OS + "</td>");
tr.append("<td>" + data[i].TotalTests + "</td>");
tr.append("<td>" + data[i].CycleRun + "</td>");
$('#GraphTable').append(tr);
lastDataWW = data[i].WW
}
And as Santi said below the comments, you could center the first column if you add this css in your style sheet.
/* CSS */
#GraphTable tr td:first-child {
text-align: center;
}

How to create table rows in for loop

I have a little issue with my For loop in Javascript. Here is my code:
$(document).ready(function() {
$.getJSON("CAN_gen_1.json", function(json) {
var tr;
for (var i = 0; i < json.messages.length; i++) {
tr = $('<tr/>');
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
tr.append("<td>" + details.signals[j].start_bit + "</td>");
tr.append("<td>" + details.signals[j].comment + "</td>");
tr.append("<td>" + details.signals[j].bit_length + "</td>");
tr.append("<td>" + details.signals[j].factor + "</td>");
tr.append("<td>" + details.signals[j].offset + "</td>");
tr.append("<td>" + details.signals[j].is_big_endian + "</td>");
tr.append("<td>" + details.signals[j].is_signed + "</td>");
tr.append("<td>" + details.signals[j].name + "</td>");
$('#table_1').append(tr);
}
}
});
});
I declare a table-row (tr). I use it each time I loop through my json file. The problem is that I get one single row with all the data.
I would like to cut the row in order to have a readable table.
Look at the snapshot : .
This is happening because you're only creating one <tr> per table.
Create your trs inside the inner loop:
$(document).ready(function() {
$.getJSON("CAN_gen_1.json", function(json) {
var tr;
for (var i = 0; i < json.messages.length; i++) {
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
tr = $('<tr/>');
tr.append("<td>" + details.signals[j].start_bit + "</td>");
tr.append("<td>" + details.signals[j].comment + "</td>");
tr.append("<td>" + details.signals[j].bit_length + "</td>");
tr.append("<td>" + details.signals[j].factor + "</td>");
tr.append("<td>" + details.signals[j].offset + "</td>");
tr.append("<td>" + details.signals[j].is_big_endian + "</td>");
tr.append("<td>" + details.signals[j].is_signed + "</td>");
tr.append("<td>" + details.signals[j].name + "</td>");
$('#table_1').append(tr);
}
}
});
});
This code is a bit unwieldy. I would suggest factoring out a function to create the rows. This way it's clear when they need to be created and you don't have to keep repeating details.signals[j]:
function tableRowForSignal(signal) {
return $('<tr />')
.append($("<td>").text(signal.start_bit));
.append($("<td>").text(signal.comment));
.append($("<td>").text(signal.bit_length));
.append($("<td>").text(signal.factor));
.append($("<td>").text(signal.offset));
.append($("<td>").text(signal.is_big_endian));
.append($("<td>").text(signal.is_signed));
.append($("<td>").text(signal.name));
}
$(document).ready(function() {
$.getJSON("CAN_gen_1.json", function(json) {
var tr;
for (var i = 0; i < json.messages.length; i++) {
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
$('#table_1').append(tableRowForSignal(details.signals[j]));
}
}
});
});
You need to create a new row for each row
tr = $('<tr/>');
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
tr.append("<td>" + details.signals[j].start_bit + "</td>");
The first of these lines needs to be inside the loop where you create the cells that go inside it.
$(document).ready(function() {
$.getJSON("CAN_gen_1.json", function(json) {
for (var i = 0; i < json.messages.length; i++) {
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
var tr = $('<tr>');
tr.append("<td>" + details.signals[j].start_bit + "</td>");
tr.append("<td>" + details.signals[j].comment + "</td>");
tr.append("<td>" + details.signals[j].bit_length + "</td>");
tr.append("<td>" + details.signals[j].factor + "</td>");
tr.append("<td>" + details.signals[j].offset + "</td>");
tr.append("<td>" + details.signals[j].is_big_endian + "</td>");
tr.append("<td>" + details.signals[j].is_signed + "</td>");
tr.append("<td>" + details.signals[j].name + "</td>");
tr.append("</tr>");
$('#table_1').append(tr);
}
}
});
});
You have to open the row before the for with
<tr>
and after all the appends you should close it with
</tr>

ajax data show in table with 10 row

I have an ajax function which select data from database base on entered information i want this information in a table having a format like this
System Id | Last Name | First Name | Middle Name | Address
Here is my ajax
$.ajax({
type: 'POST',
url: '../include/OwnerInformation.php',
dataType: "json",
data: {
lastname: last_name,
firstname: first_name,
sysid: sys_id,
address: address
},
success: function(data) {
console.log(data);
var tr = ("#searchresults");
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + "<a id=" + data[i].sys_id + " href='#' value='" + data[i].sys_id + "'>" + data[i].sys_id + "</a>" + "</td>");
tr.append("<td>" + data[i].firstname + "</td>");
tr.append("<td>" + data[i].middlename + "</td>");
tr.append("<td>" + data[i].lastname + "</td>");
tr.append("<td>" + data[i].address + "," + "</td>");
$('table').append(tr);
}
}
});
I got the tutorial for adding row here but it is not behaving like i want it to.What i want is
Result will show in a specific table (search result table) - ok
The table will have a fix number of row (10 rows)
If the result is below 10 the row will still be 10 if row is more
than 10 it will show the next 10 with next and previous button
For your number 2:
Just use
for (var i = 0; i < 10; i++)
Then if data[i] is null, you could instantiate empty values for data[i]
For your number 3:
You should edit your php so it accept something like table.php?limit=10&startRow=10 (this should fetch the second page)
first of all: The first ("#searchresults") line you forgot to add the dollar sign $. So $("#searchresults").
Secondly: You shouldn't reassign the variable for this kind of task
Finally. My solution:
var table = $("#searchresults");
for (var i = 0; i < 10; i++) {
if(data[i]==null)
data[i] = {};
var tr = $('<tr/>');
tr.append("<td>" + "<a id=" + data[i].sys_id + " href='#' value='" + data[i].sys_id + "'>" + data[i].sys_id + "</a>" + "</td>");
tr.append("<td>" + data[i].firstname + "</td>");
tr.append("<td>" + data[i].middlename + "</td>");
tr.append("<td>" + data[i].lastname + "</td>");
tr.append("<td>" + data[i].address + "," + "</td>");
table.append(tr);
}
i know it's not pretty and maybe cause some problems down the road. But hey!
var data = [
{
firstname:"Heinrich",
middlename:"Lelouch",
lastname:"Breinholdt",
address:"German smurtz"
},
{
firstname:"Cate",
middlename:"Brom",
lastname:"Lriah",
address:"Somewhere"
},
{
firstname:"Funky",
middlename:"Daddy",
lastname:"Man",
address:"Funky land"
}
];
///// You don't even need to touch this code!!!
var table = $("#searchresults");
(function(){// generate header row
var tr = $('<tr>');
if(data && data.length)
for(var key in data[0])
tr.append("<td class='table-header'>"+key+"</td>");
table.append(tr);
})();
// generate content rows
for (var i = 0; i < 10; i++) {
var tr = $('<tr>');
if(data[i])
for(var key in data[i])
tr.append("<td>" + data[i][key] + "</td>");
else
for(var key in data[0])
tr.append("<td> </td>");
table.append(tr);
}
#searchresults{
border-collapse: collapse;
}
#searchresults td{
border: 1px solid grey;
}
#searchresults .table-header{
border-bottom: 2px solid black;
padding: 3px 5px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="searchresults"></table>

Categories

Resources