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>
Related
I've copied data of a html table on page 1 in an array obj(arrData). And i've save that arrData into the session storage. Now on page 2, how do i display the data from the arrData to the html table. New in JS. Thanks in advance
PAGE 1 JS
var arrData=[];
$("#checkout").on('click',function(){
$("#table tr").each(function(){
var currentRow=$(this);
var col1_value=currentRow.find("td:eq(0)").text();
var col2_value=currentRow.find("td:eq(1)").text();
var obj={};
obj.col1=col1_value;
obj.col2=col2_value;
arrData.push(obj);
sessionStorage.myArrData=JSON.stringify(arrData);
});
console.log(arrData);
});
PAGE 2
<table class="table table-checkout" id="table">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
PAGE 2 JS
var arrData = JSON.parse(sessionStorage.myArrData);
You need to use sessionStorage.setItem("foo", 12) rather than sessionStorage.foo = 12;
The latter is attaching a new property to the javascript object, not talking to the browser session API. When the page reloads, the object you attached is gone.
To get the item back, use sessionStorage.getItem
Mozilla docs for sessionStorage including setItem and getItem
Once you've done that, you will need a way of creating new table rows in the table. There are a multitude of frameworks for this purpose, but you can also build tables (with a few more steps than with other elements) yourself
How to insert row in HTML table body in Javascript?
As I understand from above, You have data in array of objects after var arrData = JSON.parse(sessionStorage.myArrData);, in below format..
arrData:
[
{col1:"Item1", col2:"quantity1"},
{col1:"Item1", col2:"quantity1"},
...
]
Now to display this data on Page 2
var rows = "";
arrData.map((row)=>{
var row = '<tr><td>'+row.col1+'</td><td>'+row.col2+'</td></tr>';
rows = rows+row;
})
var tbody = document.queryselector('#table tbody');
tbody.innerHTML = rows;
I have a dynamically generated CSV file from another vendor that I am puling in and need to show in a table on my site. The problem is I need to be able to manipulate the data from the CSV so it can show the corrected values in the html table. In the end I need the HTML table to just display the Products, not the Mixed Sets.
I am using jquery and the papaparse library to get the data and parse it in a table in html. My codepen is here:
https://codepen.io/BIGREDBOOTS/pen/YQojww
The javascript pulls the initial csv values and display in a table, but I can't figure out how to to add together the values. If there is a better way of going about this, like converting the CSV to some other form of data like JSON, That is fine too.
My CSV looks like this:
product_title,product_sku,net_quantity
Product 1,PRD1,10
Product 2,PRD2,20
Product 3,PRD3,30
Mixed Set 1,MIX1,100
Mixed Set 2,MIX2,50
Mixed Set 3,MIX3,75
The Javascript I am using is:
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr class="rownum-' + [i] + '"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td class="' + [i] + '">'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
My rules for the mixed set:
Mixed Set 1 should add 100 to Product 1 and Product 2.
Mixed Set 2 should add 50 to Product 2 and Product 3.
Mixed Set 3 should add 75 to Product 1, Product 2 and Product 3.
I'd like to end up with Just the products output, and the correct numbers added to the formula.
The end result would be a table with Product 1 = 185, Product 2 = 245, and Product 3 = 155.
While it would be even better if the top THEAD elements were in a "th", It's fine if that is too complicated.
<table>
<tbody>
<tr class="rownum-0">
<td class="0">product_title</td>
<td class="0">product_sku</td>
<td class="0">net_quantity</td>
</tr>
<tr class="rownum-1">
<td class="1">Product 1</td>
<td class="1">PRD1</td>
<td class="1">185</td>
</tr>
<tr class="rownum-2">
<td class="2">Product 2</td>
<td class="2">PRD2</td>
<td class="2">245</td>
</tr>
<tr class="rownum-3">
<td class="3">Product 3</td>
<td class="3">PRD3</td>
<td class="3">155</td>
</tr>
</tbody>
</table>
Without knowing the size of the dataset you're working with, I suggest you first iterate through all the CSV dataset in order to populate a list of products with the correct values, and then iterate again on that to populate your HTML table:
function datasetToMap(data) {
var ret = {};
//Initialize a map with all the product rows
$(data).each(function(index, row) {
if(row[0].startsWith("Product")) {
ret[row[1]] = row; //Using the SKU as the key to the map
}
});
//Apply your mixed sets rules to the elements in the ret array
$(data).each(function(index, row) {
if(row[1] === "MIX1") {
ret["PRD1"][2] += 100;
ret["PRD2"][2] += 100;
}
//Do the same for Mixed sets 2 and 3
});
return ret;
}
function appendMapToTable(map) {
var $table = $('#my-table');
Object.keys(map).forEach(function(key, i) {
var rowData = map[key];
var row = $('<tr class="rownum-' + [i] + '"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td class="' + [j] + '">'+cellData+'</td>'));
});
$table.append(row);
});
}
$.ajax({
type: "GET",
url: "https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.csv",
success: function (data) {
appendMapToTable(datasetToMap(Papa.parse(data).data));
}
});
Note that this expects a table with id my-table to be already present in your HTML: you could manually parse the first row of your CSV data to add the table headings.
Also note that if your CSV dataset is very big this is definitely not an optimal solution, since it requires iterating through all its lines twice and then iterating again through all the list built with computed values.
A user can search for people included in a database introducing the search terms in an input text.
I am using following Ajax script to show the database objects received from JSON:
<script type="text/javascript">
$(document).ready(function() {
// With JQuery
$("#ex6").slider();
$("#ex6").on("slide", function(slideEvt) {
$("#ex6SliderVal").text(slideEvt.value);
});
$('#keyword').on('input keyup change', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length < 3) {
$('ul#content').empty()
}
if (searchKeyword.length >= 1) {
$.post('search.php', { keywords: searchKeyword }, function(data) {
$('#content').empty()
$('#content').append('<table class="table table-hover"><thead><tr><th>First Name</th><th>Last Name</th><th>Username</th></tr></thead><tbody>')
if (data == ""){
$('#content').append('No hay resultados para su búsqueda')
}
$.each(data, function() {
$('#content').append('<tr><td>'+this.nombre_doctor +'</td><td>'+ this.apellido1_doctor + '</td><td>'+ this.apellido2_doctor+'</td></tr>');
});
$('#content').append('</tbody></table>')
}, "json");
}
});
});
</script>
And this is the output when a user introduces a search term:
As you may see in the picture, the objects are not shown on the expected column.
What is wrong in the script?
When you call append with a string, jQuery constructs an object and appends that. In other words, append('<foo>') is really append($('<foo'>). The assumption in this code that append appends raw HTML is incorrect.
You want something like
var $table = $('<table class="table table-hover"><thead><tr><th>First Name</th><th>Last Name</th><th>Username</th></tr></thead></table>').appendTo('#content');
var $tbody = $('<tbody></tbody>').appendTo($table);
$.each(data, function() {
var $tr = $('<tr>').appendTo($tbody);
$('<td>').text(this.nombre_doctor).appendTo($tr);
$('<td>').text(this.apellido1_doctor).appendTo($tr);
$('<td>').text(this.apellido2_doctor).appendTo($tr);
});
// Nothing with </tbody></table> , those elements already exist
Note that your current code includes a significant vulnerability as it allows everybody who controls your data to inject arbitrary HTML and JavaScript into your website. The use of text avoids this.
You used a concate (+) function which packed all data into one column as a string. You should define 3 distinct columns to force a proper table layout.
<table width="100%" rules=groups border="0" cellspacing="0" cellpadding="0" class="table table-hover">
<colgroup>
<col width="33%" />
<col width="33%" />
<col width="33%" />
</colgroup>
Now you have a solid structure to insert your data, by column. The <th> will line up the way you have written the code.
Try building your table html as a string first, then use jquery's .html() to set it.
var htmlContents = "<table><tr><td>First column data</td><td>2nd column
data</td><td>etc</td></tr></table>";
$('#content').html(htmlContents);
That should do it.
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
I produce an int from JSON data
var f_page = ["TheHouseofMarley"];
retrieveData(f_page[0]);
function retrieveData(teamName) {
var baseURL = 'http://graph.facebook.com/';
$.getJSON(baseURL+teamName+"&callback=?", function(data) {
$('#FBlikes').append(data.likes)
});
};
and this works, it gives ~ 8407
I have a chart that reads data from < table id="chartData">
Grabbing the data from the table
I use a jQuery selector — $('#chartData td') — to select all the data cells in the table. I can then iterate through these cells with the jQuery each() method. For each cell, I determine if it's a label (e.g. "SuperWidget") or a value (e.g. "FBLike") cell, based on whether it's in the left or right column. I then store the cell contents under the 'label' or 'value' key in an associative array, which we then place inside the chartData array.
$('#chartData td').each( function() {
currentCell++;
if ( currentCell % 2 != 0 ) {
currentRow++;
chartData[currentRow] = [];
chartData[currentRow]['label'] = $(this).text();
} else {
var value = parseFloat($(this).text());
totalValue += value;
value = value.toFixed(2);
chartData[currentRow]['value'] = value;
}
// Store the slice index in this cell, and attach a click handler to it
$(this).data( 'slice', currentRow );
$(this).click( handleTableClick );
The problem is when I insert this number into < table id="chartData"> it is not read by the chart!
<table id="chartData">
<tr style="color: #0DA068">
<td>Number of Likes </td><td><span id='FBlikes'></span> </td> //Not Read!
</tr>
<tr style="color: #194E9C">
<td>MegaWidget</td><td>20000</td> //This is Read by the Chart!
</tr>
In short: Javascript output is not being read from HTML table.
Could anyone point me in some direction? I'm really new at code.
Usually this problem occurs in Ajax.
Build a string appending "data.likes" to it. Then finally assign the string to the element.
This may sound absolutely stupid, but it worked for me. Whenever i use to build a table dynamically in jQuery using the ajax response string, i would never get a table. Then i followed the procedure I mentioned.
If my solution works, some one please help me understand why is it so.