Append to table from JSON - javascript

I'm trying to get a table with data from JSON. My code looks like this:
var KrediteArray = $.parseJSON(data);
$.each(KrediteArray, function(index, item) {
$('#UserKreditsTableBody').append($('<tr id="UserKreditsTr'+index+'">'));
$.each(item, function(key, value) {
$('#UserKreditsTr' + index).append($('<td>', {
text: value
}));
});
});
KreditArray looks like this:
{
"1": {
"Admin":"Luke",
"Kapital":"100.000"
},
"2": {
"Admin":"Capto",
"Kapital":"100.000"
}
}
My Table HTML Code looks like:
<table id="UserKreditsTable">
<thead>
<tr>
<td>Name<td>
<td>Betrag<td>
</tr>
</thead>
<tbody id="UserKreditsTableBody">
</tbody>
</table>
My Problem is that in the Table I do have 2 columns at the moment (I'm gonna add more soon, along with the data from the JSON). The Script only appends one <td> to the row, so I got one cell holding all information.
Could you please give me a hint?
Edit: Have a look at the picture
(source: 666kb.com)

Try nesting another each() on key and then append each value to a <td> element.
Code should probably look like this:
var KrediteArray = $.parseJSON(data);
$.each(KrediteArray, function(index, item) {
$('#UserKreditsTableBody').append($('<tr id="UserKreditsTr'+index+'">'));
$.each(item, function(key, value) {
$.each(item, function(key, value) {
$('#UserKreditsTr' + index).append($('<td>', {
text: value
}));
});
});
});

Related

Get id from td of a table

<script type="text/javascript">
function LoadData(){
var url = serverURL+"/List.php";
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function(data){
$.each(data.data, function (key, value) {
var doc_id=value['id'];
var doc_name=value['name'];
var doc_speci = value['specialize'];
$("#myTable").append("<tr><td>"+doc_name+"</td><td>"+doc_speci+"</td><td class='retrieve' data-did="+doc_id+" style='cursor: pointer;'>EDIT</td></tr>");
});
},
error: function(data){
toastr.error("Opps! Something went wrong");
$(".se-pre-con").fadeOut("slow");
},
});
}
</script>
The above appends a tr to my html table below.
The HTML TABLE is as follows:
<table id="myTable" class='table table-bordered table-hover table-striped'>
<tr>
<th>Name</th>
<th>Specialization</th>
<th>Action</th>
</tr>
</table>
Now i want to retrieve the id from the data attribute from td class retrieve so that i can send the id and redirect it to other page for editing.
// Clicks the edit field
$("td.retrieve").on("click", function(e) {
var id = $(e.currentTarget).attr("data-did");
// do with the ID what you want
alert(id);
});
I'm aware that jQuery has a "data(...)" function but I've run into issues with that sometimes in the past. "attr(...)" will do something similar but relies specifically on the attribute instead of stored objects.
First, to add your data attribute you should make sure you add quotes around the value:
data-did='"+doc_id+"'...
So the rendered cell must look something like this:
<td class='retrieve' data-did='n' style='cursor: pointer;'>EDIT</td>
(where n is some value)
Then you can easily retrieve this value with jQuery:
$('specific-td').data('did'); //specific-td referes to a specific cell in a row, you must write that, this is just an example
To get all of the rows:
var ids = [];
$('.retrieve').each(function() {
ids.push($(this).data('did'));
});
Example:
If you have a button for example:
$('#myTable').on('click', '.retrieve input[type="button"]', function() {
var id = $(this).parent().data('did');
alert(id);
});
JSFiddle: https://jsfiddle.net/y2an0fu7/1/

populating table with jquery and json

I would like to populate an existing table with json data. I found an example on stackoverflow which does this but with only one column of data. The json data has three sets of data which requires obviously 3 columns. I have experimented with only one row but the jquery code (below) incorrectly displays the table.
<table class="table">
<tr id="row1">
<td = "col1"></td>
<td = "col2"></td>
<td = "col3"></td>
function myFunction() {
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];
$.each(data, function(key, value) {
$("#row1").eq(key).find('td').text(value.indx);
$("#row1").eq(key).find('td').text(value.amt);
$("#row1").eq(key).find('td').text(value.jDate);
});
}
OUTPUT IN BROWSER: 167 167 167
It is displaying the last field in all three columns. Any advise on how to do get table to display the correct values would be appreciated.
Your code is updating ALL CELLS with value.indx, then with value.amt and finally with value.jDate... So fast that you only see the final result.
I think what you want to achieve is something more like in this CodePen :
function myFunction() {
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];
$.each(data, function(key, value) {
$("table").find('tr').eq(key).find("td").eq(0).text(value.indx);
$("table").find('tr').eq(key).find("td").eq(1).text(value.amt);
$("table").find('tr').eq(key).find("td").eq(2).text(value.jDate);
});
}
myFunction();
Obviously you have to add rows dynamically into your table, because your data array may contain different amount of objects.
Try this code.
Here we have table which is populated with new rows for each element of data array.
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3344.4,"vendor":22,"jDate":168},
{"indx":3,"amt":1414.1,"vendor":21,"jDate":169},
{"indx":4,"amt":3441.3,"vendor":31,"jDate":1610}];
$.each(data, function(key, value) {
var tr = $("<tr>");
tr.append($("<td>").text(value.indx));
tr.append($("<td>").text(value.amt));
tr.append($("<td>").text(value.vendor));
tr.append($("<td>").text(value.jDate));
$("#table").append(tr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table" border="1">
</table>

Populate Existing Table With Data Using JQuery

Using the method below I am trying to populate an existing table with data however the function fills it with the same values. I can perform such action adding append method, but in my case the table should be exist already :)
HTML
<table class="table">
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td></td></tr>
</table>
JQuery
$.each(data, function(i, value){
$(".table td").text(value.product);
});
var data= [
{"product":"RD0"},
{"product":"RD1-184"},
{"product":"RD1-185"}
]
Here's a code snipped using your sample from above with a demo in JSFiddle.
$(function() {
var data = [{
"product": "RD0"
}, {
"product": "RD1-184"
}, {
"product": "RD1-185"
}];
var table = $('.table');
$.each(data, function(i, value) {
table.find('tr').eq(i).find('td').text(value.product);
});
});
https://jsfiddle.net/qur62os2/
you probably need something like this:
$(".table").find('td').each(function(i) {
$(this).text(data[i].product);
});
https://jsfiddle.net/ahmadabdul3/fn8q8e3x/

JSON to html STYLED table

We can convert a set of JSON data to html table by below code:
$.each(data, function(key, val) {
var tr=$('<tr></tr>');
$.each(val, function(k, v){
$('<td>'+v+'</td>').appendTo(tr);
});
tr.appendTo('#display');
});
The html table is:
<table border='1' id="display">
<thead>
<tr>
<th>firstcol</th>
<th>loc</th>
<th>lastA</th>
<th>mTime</th>
<th>nTime</th>
<th>Age</th>
<th>ction</th>
</tr>
</thead>
</table>
A working example at: http://jsfiddle.net/AHv6c/ (source jquery code to display json response to a html table using append)
My problem is when some of the rows columns could have their own style class.
So I want to change some of the the table <th> to <th class='sampleStyle'> . Can you please let me know how should I change the java script to read the corresponding class from th and assign it to relevant columns (s).
Then the generated table should be something like:
<tr>
<td>56036</td>
<td class="sampleStyle">Deli</td>
....
By the way do you know better approach?
You may try something like http://www.jqversion.com/#!/Mdi8Kla
$.each(data, function(key, val) {
var tr = $('<tr></tr>'),
index = 0;
$.each(val, function(k, v){
$('<td>'+v+'</td>').addClass(
$('th:eq(' + index + ')').attr('class')
).appendTo(tr);
index++;
});
tr.appendTo('#display');
});
$("td:eq(0)", tr).addClass("sampleStyle");
before appending tr

Creating table from API

My function is pulling information from an api and then putting it into the table. For some reason this function is not working.
this is my function:
function getPayInfo(socCode) {
var apiurl = "http://api.lmiforall.org.uk/api/v1/ashe/estimatePay?soc=";
var apicall = apiurl + socCode;
$.get(apicall, function(data) {
$("#Pay tbody").html("");
$.each(data.years, function(i, e) {
var tablerow = $("<tr></tr>");
tablerow.append("<td>" + e.year + "</td>");
tablerow.append("<td>" + e.estpay + "</td>");
$("#Pay tbody").append(tablerow);
});
});
}
and this is the table I am putting it into:
<div class="well table table-stripped">
<h4>Pay Information</h4>
<h5>Pounds per Week</h5>
<table id="Pay">
<thead>
<tr>
<th>Year</th>
<th>Estimate Pay</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I expected it to return a year and data value into the table. if you take the url in the function and add a certain 4 figure value (the socCode) (e.g. 5113) to the end it will give the data online this should then be returned to the table body.
Have you debugged/examined the data structure inside your $.get callback? It looks to me that your access method is incorrect. When I access your example url, I get the following data back:
{
"soc":5113,
"series":[
{
"year":2012,
"estpay":340
}
]
}
I think you want your iterator to be this instead:
// there is no data.years
$.each(data.series, function(i, e) {
...
This should make your e param be of the form {year: 2012, estpay: 340}, which appears to be what you want to interpret it as.

Categories