JSON to html STYLED table - javascript

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

Related

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>

Append to table from JSON

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
}));
});
});
});

Trying to populate an html table using Jquery array

I need to know how can i add a row in this table for each one of the values of the checked checkboxes.
<table class="table table-striped table-hover table-responsive" id="sel_articulos">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody></tbody>
</table>
I'm saving a list of checked checkboxes with this code in an array.
$('#modalarticulos').on('hidden.bs.modal', function () {;
var sel_articulos = $("input[name='check_art']:checked").map(function () {
return this.value;
}).get();
console.log(sel_articulos);
showSels();
})
tried with this method but i get all the values from the array in the response
var tbody = $('#sel_articulos tbody');
var props = ["id"];
$.each(sel_articulos, function(i, sel_articulo) {
var tr = $('<tr>');
$.each(props, function(i, prop) {
$('<td>').html(sel_articulos).appendTo(tr);
});
tbody.append(tr);
});
I.E: If i select 5 values i get this on every row of my table.
112113114115117

Highlight some rows of my table in javascript

I need to highlight some rows of my table. This highlight is based on the rows present in my response object. This object can be as follow:
<table id="ListRequests" class="table table-striped">
<tbody>
<tr id="13955">
<td>JEAN DUPONT</td>
<td>ACLIMEX SPRL</td>
</tr>
</tbody>
</table>
Here is my javascript code:
var id = $("tbody tr", response).attr('id');
var cols = $('#' + id + ' td');
cols.effect("highlight", {}, 30000);
This works fine only if my response object contains only 1 row. Now I need to be able to highlight more than 1 rows at a time. So for example with the response object below:
<table id="ListRequests" class="table table-striped">
<tbody>
<tr id="13955">
<td>JEAN DUPONT</td>
<td>ACLIMEX SPRL</td>
</tr>
<tr id="13954">
<td>MIKE GIVER</td>
<td>ARGO INTERNATIONAL CORP</td>
</tr>
</tbody>
</table>
Any idea how to adapt my javascript code for that purpose ?
If you really want to do it the way you are doing it, than you need to use each
var trs = $("tbody tr", response);
trs.each( function () {
var id = this.id,
cols = $('#' + id + ' td');
cols.effect("highlight", {}, 30000);
});
Better off returning a JSON object with ids to select.
attr returns a single value, regardless how many elements are matched by the proceeding selector.
If you want to map every selected element to an ID and return array, you need map:
var ids = $("tbody tr", response).map(function (i, e) { return $(e).attr('id'); });
Once you have your list of IDs, you can iterate over that list, and highlight the matching rows in the DOM:
ids.forEach(function (id) {
var cols = $('#' + id + ' td');
cols.effect("highlight", {}, 30000);
});
Here is a working snippet.
The idea is to scrap the ids from the response you get by looping the tr nodes, from these ids build a css selector for the nodes you are interested in, and finally highlight all them.
function highlight(response){
// retrieve the ids from the response
var ids = $(response).find("tbody tr").map(function(){
// `this` will be the trs one after the other.
// `map` will put all returned values in an array.
return this.getAttribute("id");
}).get();
// build the css selector
var selector = "#" + ids.join(",#");
// highlight the corresponding nodes
$(selector).effect("highlight", {}, 30000);
}
// Call highlight with your response example.
highlight('<table id="ListRequests" class="table table-striped"><tbody><tr id="13955"><td>JEAN DUPONT</td><td>ACLIMEX SPRL</td></tr><tr id="13954"><td>MIKE GIVER</td><td>ARGO INTERNATIONAL CORP</td></tr></tbody></table>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<table id="ListRequests" class="table table-striped">
<tbody>
<tr id="13955">
<td>JEAN DUPONT</td>
<td>ACLIMEX SPRL</td>
</tr>
<tr id="13954">
<td>MIKE GIVER</td>
<td>ARGO INTERNATIONAL CORP</td>
</tr>
<tr id="1211">
<td>OTHER ONE</td>
<td>MUSN'T BE HIGHLIGHTED</td>
</tr>
</tbody>
</table>

table mapping by th and first td in row to populate from json object

using php to echo json array inline i want js/jquery to populate table according to these data.
HTML table
<table>
<thead>
<tr>
<th>Time</th>
<th data-day='2013-03-15'>15-3</th>
<th data-day='2013-03-16'>16-3</th>
<th data-day='2013-03-17'>17-3</th>
</tr>
</thead>
<tbody>
<tr data-time='09'>
<td>9am</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script>
var arr=[
{"date":"2013-03-15","id":"4","time_booked":"09:00:00"},
{"date":"2013-03-15","id":"1","time_booked":"09:10:00"},
{"date":"2013-03-17","id":"5","time_booked":"09:30:00"}
];
$.each(arr,function(){
console.log('id:'+this.id+'inside:'+this.date+'|'+this.time_booked);
});
</script>
i want to loop thro arr and according to its date and time_booked write id inside td.
for example first row will go to td with date-day='2013-03-15' and data-time='09'
so how can i do this using javascript ?
im thinking should i include data-day,data-time inside each td in tbody ? or is there a better way to do it ?
current approach:
include data-day inside each tr so html of tbody is
<tr data-time='09'>
<td data-day='2013-03-15'></td>
<td data-day='2013-03-16'></td>
etc..
</tr>
then use js
$.each(arr,function(){
var rday=this.date;
var rtime=this.time_booked;
var sel='tr[data-hr="'+rtime.substr(0,2)+'"]';
var dom=$(sel).find('td[data-day="'+rday+'"]').first();
if(dom.length)dom.append(this.id);
});
but i have a feeling its stupid ! there must be a way to map table using x,y (table head,row head) or there is none ?
I think the jQuery index function is what you're looking for. In the code sample below, I've used it to fetch the colIndex for the date. In this case, it fetches all of the th cells within the table, and uses .index(..) with a selector seeking the required date. This gives the column index of the date you're seeking, and from there it's all pretty straight-forward.
var arr=[
{"date":"2013-03-15","id":"4","time_booked":"0900"},
{"date":"2013-03-15","id":"1","time_booked":"0910"},
{"date":"2013-03-17","id":"5","time_booked":"0930"}
];
$.each(arr,function(){
var cell = GetCellByDateAndTime(this.date, this.time_booked);
$(cell).text(this.id);
});
function GetCellByDateAndTime(date, time) {
var colIndex = $("#BookingsTable th").index($("[data-day='" + date + "']"));
var row = $("#BookingsTable tr[data-time='" + time + "']")
var cell = $(row).children($("td"))[colIndex];
return cell;
}
And a Fiddle.

Categories