Update totals in a table - javascript

I have:
$('#createStockOrder').click(function () {
modal('create-stock-order', {}, function () {
var $modal = $(this);
var submitted = false;
var model = [];
$('.glyphicon-plus').click(function () {
var product_id = $('#productSelect option:selected').text(),
size_id = $('#sizeSelect option:selected').text(),
colour_id = $('#colourSelect option:selected').text(),
quantity = $('#quantity').val();
// Get index of the element where all the fields matches
var index = getObjectIndex(model, product_id, size_id, colour_id);
// If object found in the array
if (index !== false) {
// Update the quantity in the same element
model[index].quantity = quantity;
} else {
// Add the element in the array
model.push({
product_id: product_id,
size_id: size_id,
colour_id: colour_id,
quantity: quantity
});
}
printStock(model);
});
var form = document.getElementById('create_sale');
var $form = $(form);
$form.on('submit', function (e) {
e.preventDefault();
if (!submitted) {
submitted = true;
$('#create_sale .btn-primary').addClass('disabled');
var formData = new FormData(form);
qwest.post(form.action, formData)
.then(function (resp) {
$modal.modal('hide');
})
.catch(function (xhr, response, e) {
var html = '';
$.each(response, function (i, v) {
html += '<p>' + v + '</p>';
});
$('#create_sale .alert').html(html).removeClass('hide');
$('#create_sale .btn-primary').removeClass('disabled');
submitted = false;
});
}
})
}, {width: 1000});
});
// Currently the function is Static, but it can be changed to dynamic
// by using nested loop and a flag to store the match status
function getObjectIndex(arr, product_id, size_id, colour_id) {
// Loop over array to find the matching element/object
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
if (obj.product_id === product_id && obj.size_id === size_id && obj.colour_id === colour_id) {
// When all key-value matches return the array index
return i;
}
}
// When no match found, return false
return false;
}
function printStock(model) {
var html = '';
var total_row_quantity = 0;
var total_row_value = 0;
$.each(model, function (i1, v1) {
html += '<tr>';
$.each(v1, function (i2, v2) {
html += '<td>' + v2 + '</td>';
$('#product_totals tr').each(function(i3, v3){
var product_code = $('td', v3).eq(0).html();
if(product_code == v2) {
total_row_quantity += parseInt(model[i1].quantity);
total_row_value += parseFloat($('td', v3).eq(2).html()*model[i1].quantity);
$('td', v3).eq(1).html(total_row_quantity);
$('td', v3).eq(3).html(accounting.formatMoney(total_row_value, ''));
} else {
total_row_quantity = 0;
total_row_value = 0;
}
})
});
html += '</tr>';
});
$('#stock_order tbody').html(html);
}
The HTML is:
<tbody id="product_totals">
<tr data-id="1">
<td>JW1501</td>
<td class="code-quantity-total">0</td>
<td>79.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="2">
<td>JW1502</td>
<td class="code-quantity-total">0</td>
<td>99.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="3">
<td>JW1501-1</td>
<td class="code-quantity-total">0</td>
<td>20.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="4">
<td>JW1502-2</td>
<td class="code-quantity-total">0</td>
<td>25.00</td>
<td class="code-cost-total">0</td>
</tr>
</tbody>
The list of rows (JW1501, JW1502) is dynamic.
The problem I am having is that if a variant of e.g. JW1502 is added, only the total quantity and value is calculated for that one. Any previous different variants of JW1502 are ignored.
How can I fix this?
Example content of var model:
[
{"product_id":"JW1501","size_id":"70A","colour_id":"小豹纹","quantity":"1"},
{"product_id":"JW1501","size_id":"75B","colour_id":"小豹纹","quantity":"2"},
{"product_id":"JW1502","size_id":"85A","colour_id":"黑色","quantity":"1"}
]
The above for JW1501 would show the incorrect quantity of 2, not 3.
...
$('#product_totals tr').each(function (i3, v3) {
console.log(v1, v2, v3)
...
Outputs:
Object {product_id: "JW1501", size_id: "70A", colour_id: "小豹纹", quantity: "2"}
"JW1501"
<tr data-id=​"1">​<td>​JW1501​</td>​<td class=​"code-quantity-total">​2​</td>​<td>​79.00​</td>​<td class=​"code-cost-total">​158.00​</td>​</tr>​

I have completely changed your printStock function to achieve your goal:
function printStock(model) {
$("#product_totals tr").each(function(){
var id = $("td:eq(0)", this).text().trim();
var price = parseFloat($("td:eq(2)", this).text());
var count = 0;
$.each(model, function(i, item){
if (item.product_id == id) count += (+item.quantity);
});
$("td:eq(1)", this).text(count);
$("td:eq(3)", this).text((count * price).toFixed(2));
});
var rows = $.map(model, function(item){
return [
"<td>" + item.product_id + "</td>",
"<td>" + item.size_id + "</td>",
"<td>" + item.colour_id + "</td>",
"<td>" + item.quantity + "</td>"
].join("");
});
var html = "<tr>" + rows.join("</tr><tr>") + "</tr>";
$('#stock_order tbody').html(html);
}
The main difference is that my code groups items in model by product_id for further counting.
Also refer my fiddle.

Related

Sorting table using only Javascript

I have this table in which I read the tbody contents from a JSON API and now I need to make it sortable by columns and using only javascript and no Jquery.
Any help would be appreciated
i have found this code which is exactly what i want, but i don't know how to refer to tbodies from my api
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'https://jsonplaceholder.typicode.com/todos');
myRequest.onload = function () {
var myData = JSON.parse(myRequest.responseText);
dataTable(myData);
};
myRequest.send();
function dataTable(data) {
if (data.length > 0) {
var temp = '';
data.forEach((u) => {
temp += '<tr>';
temp += "<td style='text-align: center'>" + u.userId + '</td>';
temp += "<td style='text-align: center'>" + u.id + '</td>';
temp += '<td>' + u.title + '</td>';
temp += "<td style='text-align: center'>" + u.completed + '</td></tr>';
document.getElementById('data').innerHTML = temp;
});
}
}
<table class="table_id">
<thead>
<tr>
<th>UserID</th>
<th>ID</th>
<th>Title</th>
<th>Completion</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
var myData, asc = {'userId':true, 'id':true, 'title':true, 'completed':true};
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'https://jsonplaceholder.typicode.com/todos');
myRequest.onload = function () {
myData = JSON.parse(myRequest.responseText);
dataTable(myData);
};
myRequest.send();
function sortTable(key){
myData.sort(function(a, b) {
if(asc[key]){
return a[key] > b[key]? 1:-1;
}
else{
return a[key] > b[key]? -1:1;;
}
});
asc[key] = !asc[key];
document.getElementById('data').innerHTML = '';
dataTable(myData);
}
function dataTable(data) {
if (data.length > 0) {
var temp = '';
data.forEach((u) => {
temp += '<tr>';
temp += "<td style='text-align: center'>" + u.userId + '</td>';
temp += "<td style='text-align: center'>" + u.id + '</td>';
temp += '<td>' + u.title + '</td>';
temp += "<td style='text-align: center'>" + u.completed + '</td></tr>';
document.getElementById('data').innerHTML = temp;
});
}
}
<table class="table_id">
<thead>
<tr>
<th onclick="sortTable('userId');">UserID</th>
<th onclick="sortTable('id');">ID</th>
<th onclick="sortTable('title');">Title</th>
<th onclick="sortTable('completed');">Completion</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
Here is a quick class I made.
You first load your data with dt.load(), then when someone clicks one of the headers, you can add an event that does:
elm.addEventListener("click", (e) => {
prop = e.target.textContent.trim();
dt.sort(prop);
dt.render();
})
class DataTable{
load(arr){
if(arr) this.data = arr;
}
sort(prop){
this.data.sort((a, b) => a[prop] - b[prop]);
}
render(selector="#data"){
if(data.length){
html = data.map(u => {
return [
"<tr>",
`<td style='text-align: center'>${u.userId}</td>`,
`<td style='text-align: center'>${u.id}</td>`,
`<td>${u.title}</td>`,
`<td style='text-align: center'>${u.completed}</td></tr>`
].join("");
}).join("");
document.querySelector(selector).innerHTML = html;
}
}
}
Important - are you wanting to be able to sort multiple columns at the same time or just one column at a time?
Initialize myData outside of onload first. You'll want to be able to access those results outside of onload to sort them. The actual sort function JS offers is a pretty confusing but it's really the only way to go about vanilla JS array sorting.
function sortData(col, asc = true) {
//JS sort function
myData = myData.sort((first, second) => {
//sort logic
if (first[col] == second[col]) {
return 0;
}
if (asc) {
if (first[col] > second[col]) {
return 1;
}
else {
return -1;
}
}
else {
if (first[col] > second[col]) {
return -1;
}
else {
return 1;
}
}
});
//Re-Create table
dataTable(myData);
}
EDIT:
I added in sort logic, but it's definitely possible I messed up. I can't actually test this right now and I haven't touched the sort function in years.

Search function to include space

I am trying to build a search function that would allow me to search Word 1 Word 2 ... Word 'n'.
The code below allows me to search through table rows. Results are presented when there is a 1:1 match (Ignoring case). I would like to search using combinations separated by spaces.
Table data sample as below.
AAA_BBB_CCC_DDD.pdf
EEE_FFF_GGG_HHH.pdf
HTML
<script>
$(function(){
$(function(){
var requestUri = "<<URL>>/_api/web/GetFolderByServerRelativeUrl('<<Folder>>')/Files?$filter=(substringof(%27.pdf%27,Name)%20or%20substringof(%27.PDF%27,Name))&$top=1000";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="Table" style="width:100%"><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + [i+1] + '</td>';
tableContent += '<td>' + objItems[i].Name + '</td>';
tableContent += '<td>' + "<a target='iframe_j' href='<<URL>>" + objItems[i].ServerRelativeUrl + "'>" + "View" + "</a>" + '</td>';
tableContent += '</tr>';
}
$('#TDGrid').append(tableContent);
}
});
});
</script>
<div id="div">
<input class="form-control mb-2" id="TDSearch" type="text" placeholder=" Search">
<table id='Table' class="table table-striped table-sm small">
<tr>
<td>
<div id="TDGrid" style="width: 100%"></div>
</td>
</tr>
</table>
</div>
Current search function
$(document).ready(function(){
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#TDGrid tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
You can convert string to array and then make a function, which will check match for strings of that array.
Something like
$(document).ready(function() {
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
var valueArr = value.split(' ');
$("#TDGrid tr").filter(function() {
$(this).toggle(checkIfValuePresent($(this).text().toLowerCase(), valueArr));
});
});
});
function checkIfValuePresent(currRowText, valuesarr) {
let isfound = false;
for (let i = 0; i < valuesarr.length; i++) {
if (currRowText.indexOf(valuesArr[i] > -1)) {
isfound = true;
break;
}
}
return isfound;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='TDSearch'>
split on space, join all strings with | between them for a combined regex string search, case insensitive.
$(document).ready(function(){
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#TDGrid tr").filter(function() {
$(this).toggle(new RegExp(value.replace(/\./g,'[.]').split(' ').join('|'),'gi').test($(this).text()))
});
});
});

Count the results returned in an AJAX call from selected parent

My first pop up list distinct customers with distinct cust_id from the AJAX call. I'm trying to get the count of the number of rows with cust_id that are the same as the selected customer.
For example: If I select "Jeffs Music" from the distinct list I need the count to return 5 since there are 5 rows that cust_id = "15"
$('.add-invoice').live('click', function() {
$("#invoice_div").css("display", "block");
$.ajax({
url: 'invoice_fill.php',
data: {
action: "invoice"
},
dataType: 'json',
success: function(data) {
var result = [];
$.each(data, function(i, e) {
var matchingItems = $.grep(result, function(item) {
return item.customer === e.customer && item.cust_id === e.cust_id;
console.log(item.cust_id);
});
if (matchingItems.length === 0) {
result.push(e);
}
});
var xyz = (JSON.stringify(result));
console.log(xyz);
populateSelectBoxes($('#invoice_div #ddinvoice'), result);
function populateSelectBoxes($select, result) {
var invoices = [];
$.each(result, function() {
invoices.push('<li data-value="' + this.cust_id + '">' + this.customer + ' : ' + this.invoice + '</li>');
});
$select.append(invoices.join(''));
}
function populateTableRow(data, selectedProductAutonum) {
var invoices;
$.each(result, function() {
if (this.cust_id == selectedProductAutonum) {
invoices = this;
var arr = this.cust_id;
var occurrences = {};
for (var i = 0, j = arr.length; i < j; i++) {
occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;
}
console.log(occurrences);
return false;
// changed autonun to cust_id to give unique record/product call (changed in line 248 as well)
}
});
$(".item-row:last").after(
'<tr class="item-row"><td class="item-name"><div class="delete-wpr"><textarea form ="testinsert" name="item_name[]">Item Name</textarea><a class="delete" href="javascript:;" title="Remove row">X</a><a class="add-product" href="javascript:;" title="Add Product">A</a></div></td><td class="description"><textarea form ="testinsert" name="item_desc[]">Description</textarea></td><td><textarea class="cost" form ="testinsert" name="item_cost[]">$0</textarea></td><td><textarea class="qty" form ="testinsert" name="item_qty[]">0</textarea></td><td><span class="price" form ="testinsert" name="item_price[]">$0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
$('#address-title').val(invoices.customer);
$('#address-one').val(invoices.address);
//$('#address-two').val(invoices.sales + '\n' + invoices.owed);
//$('#address-three').val(invoices.address3);
///////////////////////////////////////////
$('#invoice_num').val(invoices.invoice);
$('#paid').val(invoices.paid);
$('#owed').val(invoices.sales);
$('#auto_num').val(invoices.autonum);
///////////////////////////////////////////
$('[name="item_name[]"]').val(invoices.product);
$('[name="item_desc[]"]').val(invoices.description);
$('[name="item_cost[]"]').val(invoices.cost);
$('[name="item_qty[]"]').val(invoices.quantity);
$('[name="item_price[]"]').val(invoices.price);
}
$('#invoice_div #ddinvoice li').click(function(e) {
var selection = $(this).attr("data-value");
$(this).parent().parent().parent().hide();
populateTableRow(data, selection);
$('ul').empty();
});
}
});
update_total();
});
Look at this jsFiddle for full code. That should be clear, however the AJAX calls are not working in it?

Two scripts pulling data from an API work individually but not when on the same page

I've got a JS script that pulls data from an API and merges it all into a table, I need to do this twice for two different sets of data. Individually the scripts work as expected but when they're running on the same page only one of them displays any data.
I know the script tag isn't the best way to use JS but for my purpose everything needs to be contained in one block of html.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
//Voting totals for current month
var votingURLs = [
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=7ImLVCEQFgOq9Ugz5G569nQJ5akmta8C2ty&month=current&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=eJgmsMaw6Aor1bSD1r9wtyu1mBiLNjWSZW&month=current&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=current&format=json&rank=steamid'
];
var votingLists = [];
var counter = 0;
var finalList = [];
var voters = [];
var votesOfVoters = [];
$(document).ready(function() {
$.each(votingURLs, function(index, value) {
var data;
$.ajax({
dataType: "json",
url: value,
data: data,
success: function(data) {
votingLists[index] = data.voters;
checkCompleteness();
}
});
});
});
function checkCompleteness() {
counter++;
if (counter == (votingURLs.length)) {
evalData();
}
}
function evalData() {
console.log("Start Evaluating");
finalList = votingLists[0];
$.each(votingLists, function(index, list) {
if (index > 0) {
$.each(list, function(index, value) {
var steamid = value.steamid;
var found = false;
$.each(finalList, function(indexF, valueF) {
if (steamid == valueF.steamid) {
valueF.votes = parseInt(valueF.votes) + parseInt(value.votes);
found = true;
return false;
}
});
if (!found) {
finalList.push(value);
}
});
}
});
displayingList(finalList);
}
function displayingList(list) {
console.log("Start Displaying");
list.sort(function(a, b) {
return parseInt(b.votes, 10) - parseInt(a.votes, 10);
});
$.each(list, function(index, value) {
var row = '<tr> <td>' + value.nickname + '</td> <td> ' + value.votes + '</td> </tr>';
$('table[data="current_votes"] tbody').append(row);
});
}
</script>
<script>
//Voting totals for previous month
var votingURLs = [
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=7ImLVCEQFgOq9Ugz5G569nQJ5akmta8C2ty&month=previous&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=eJgmsMaw6Aor1bSD1r9wtyu1mBiLNjWSZW&month=previous&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=previous&format=json&rank=steamid'
];
var votingLists = [];
var counter = 0;
var finalList = [];
var voters = [];
var votesOfVoters = [];
$(document).ready(function() {
$.each(votingURLs, function(index, value) {
var data;
$.ajax({
dataType: "json",
url: value,
data: data,
success: function(data) {
votingLists[index] = data.voters;
checkCompleteness();
}
});
});
});
function checkCompleteness() {
counter++;
if (counter == (votingURLs.length)) {
evalData();
}
}
function evalData() {
console.log("Start Evaluating");
finalList = votingLists[0];
$.each(votingLists, function(index, list) {
if (index > 0) {
$.each(list, function(index, value) {
var steamid = value.steamid;
var found = false;
$.each(finalList, function(indexF, valueF) {
if (steamid == valueF.steamid) {
valueF.votes = parseInt(valueF.votes) + parseInt(value.votes);
found = true;
return false;
}
});
if (!found) {
finalList.push(value);
}
});
}
});
displayingList(finalList);
}
function displayingList(list) {
console.log("Start Displaying");
list.sort(function(a, b) {
return parseInt(b.votes, 10) - parseInt(a.votes, 10);
});
$.each(list, function(index, value) {
var row = '<tr> <td>' + value.nickname + '</td> <td> ' + value.votes + '</td> </tr>';
$('table[data="old_votes"] tbody').append(row);
});
}
</script>
<div>
<table data="current_votes" id="current_totals">
<tr>
<th colspan="2">Totals</th>
</tr>
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
<div>
<table data="old_votes" id="old_totals">
<tr>
<th colspan="2">Totals</th>
</tr>
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
please take a look of below code. i added one extra parameter to distinguish current and old url and based on that in displayingList() we append data.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
//Voting totals for current month
var current_votingURLs = [
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=7ImLVCEQFgOq9Ugz5G569nQJ5akmta8C2ty&month=current&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=eJgmsMaw6Aor1bSD1r9wtyu1mBiLNjWSZW&month=current&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=current&format=json&rank=steamid'
];
var old_votingURLs = [
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=7ImLVCEQFgOq9Ugz5G569nQJ5akmta8C2ty&month=previous&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=eJgmsMaw6Aor1bSD1r9wtyu1mBiLNjWSZW&month=previous&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=previous&format=json&rank=steamid'
];
var votingLists = [];
var counter = 0;
var finalList = [];
var voters = [];
var votesOfVoters = [];
var apiCounter = 0;
$(document).ready(function() {
function baseFunction(votingURLs, urlType){
$.each(votingURLs, function(index, value) {
var data;
$.ajax({
dataType: "json",
url: value,
data: data,
success: function(data) {
apiCounter++;
console.log(data);
votingLists[index] = data.voters;
checkCompleteness(votingURLs, urlType);
}
});
});
}
baseFunction(current_votingURLs,'current');
baseFunction(old_votingURLs,'old');
});
function checkCompleteness(votingURLs, urlType) {
counter++;
console.log('In checkCompleteness');
//if (counter == (votingURLs.length)) {
evalData(urlType);
//}
}
function evalData(urlType) {
console.log("Start Evaluating");
console.log("Start Evaluating", urlType);
finalList = votingLists[0];
$.each(votingLists, function(index, list) {
if (index > 0) {
$.each(list, function(index, value) {
var steamid = value.steamid;
var found = false;
$.each(finalList, function(indexF, valueF) {
if (steamid == valueF.steamid) {
valueF.votes = parseInt(valueF.votes) + parseInt(value.votes);
found = true;
return false;
}
});
if (!found) {
finalList.push(value);
}
});
}
});
displayingList(finalList, urlType);
}
function displayingList(list, urlType) {
console.log("Start Displaying");
console.log("urlType", urlType);
list.sort(function(a, b) {
return parseInt(b.votes, 10) - parseInt(a.votes, 10);
});
if(urlType == 'current') {
$.each(list, function(index, value) {
var row = '<tr> <td>' + value.nickname + '</td> <td> ' + value.votes + '</td> </tr>';
$('table[data="current_votes"] tbody').append(row);
});
}else {
$.each(list, function(index, value) {
var row = '<tr> <td>' + value.nickname + '</td> <td> ' + value.votes + '</td> </tr>';
$('table[data="old_votes"] tbody').append(row);
});
}
console.log(apiCounter);
}
</script>
<div>
<table data="current_votes" id="current_totals">
<tr>
<th colspan="2">Totals</th>
</tr>
<tr>
<th>Username new</th>
<th>Votes</th>
</tr>
</table>
</div>
<div>
<table data="old_votes" id="old_totals">
<tr>
<th colspan="2">Totals</th>
</tr>
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>

Converting JSON array in HTML table using JQuery

My JSON Array containing date and key-value pairs of alphabets. I need columns as date values and rows heading as Alphabets.
{
"error":0,
"data":[
{
"date":"2017-12-01",
"A":1,
"B":2
},
{
"date":"2017-12-02",
"A":2,
"B":3
}
]
}
I want to create table as given below
Alpha 2017-12-01 2017-12-02
A 1 2
B 2 3
My HTML Code containing datatable for table formatting:
<table id="report" class="table table-striped table-bordered">
<thead>
<tr>
<th>Alpha</th>
</tr>
</thead>
<tbody></tbody>
</table>
And JQuery ajax get response that calls the API:
$.ajax({
url: 'userData/01/2018',
success: function(response) {
let reportData = response.data;
let i = 0;
let j = 1;
let k = 0;
let table = document.getElementById('report');
let tr = table.tHead.children[0];
reportData.forEach(function(data) {
let row = table.insertRow(j);
if (i == 0) {
let th = document.createElement('th');
th.innerHTML = data.date;
tr.appendChild(th);
}
if (k == 0) {
let keys = Object.keys(data);
for (let p = 1; p < keys.length; p++) {
let cell = row.insertCell(k);
cell.innerHTML = keys[p];
for (let q = 1; q < keys.length; q++) {}
}
}
});
}
});
I am able to insert headers as table columns but facing an issue in data insertion.
slight changes in your json string,
HTML:
<table id="report"></table>
JavaScript:
var jsonString = '{"error": 0,"Alpha": [{"date": "2017-12-01","A": 1,"B": 2},{"date": "2017-12-02","A": 2,"B": 3}]}';
var s = '';
$.each(JSON.parse(jsonString), function(i, j) {
if (i == 'Alpha') {
s += '<thead><th>' + i + '</th>';
$.each(j, function(k, val) {
s += '<th>' + val.date + '</th>';
});
s += '</thead>';
$('#report').html(s);
for (var l = 0; j.length; l++) {
if (l == 0) {
s = '<tbody><tr><td> ' + Object.keys(j[l])[l + 1] + ' </td>';
s += '<td> ' + j[l].A + ' </td><td>' + j[l].B + '</td></tr>';
$('#report').append(s);
} else {
s = '<tr><td>' + Object.keys(j[l])[l + 1] + '</td><td>' + j[l].A + '</td><td>' + j[l].B + '</td></tr>';
$('#report').append(s);
}
s += '</tbody>';
}
}
});
For reference - https://jsfiddle.net/zvxqf9mz/

Categories

Resources