Howto use Boostrap table to get column sum using external json file - javascript

I have the following bootstrap based table and I am trying to calculate the total MarketValue. Its reading an external json file. but for some reason its not adding the values.
the problem starts when i load an external json. file. How can i fix this?
$.getJSON("json/prep.json", function (jsonFromFile) {
$('#table1').bootstrapTable({
data: jsonFromFile.rows
})
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue);
}, 0);
document.querySelector('.total1').innerHTML = total1;
});
JSON - prep.json
{
"Name": "Julie Brown",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "1000",
"MaxApprovedLoanAmt": "10000",
"LoanBalance": "1849000",
"AvailableCredit": "2877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "oJohnson",
"ContactPhone": "-3614",
"RiskCategory": "Yellow",
"rows": [{
"Account": "086-1234",
"ClientName": "S Smth",
"AccountType": "tail",
"LongMarketValue": "$40000"
}, {
"Account": "086-1235",
"ClientName": "all Sth",
"AccountType": "REV Trust",
"LongMarketValue": "$55000"
},
{
"Account": "086-1236",
"ClientName": "Sly Smith",
"AccountType": "Reail",
"LongMarketValue": "$5500"
}]
}
HTML
<table id="table1">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Account">Account #</th>
<th data-field="ClientName">Client</th>
<th data-field="AccountType">Account Type</th>
<th data-field="MarketValue"> Market Value</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<th></th>
<th> Total <span class="total1"></span></th>
</tr>
</tfoot>
</table>

data is undefined in your code, you have to retrieve data from table or from Json. Also your data returns a string with $ sign, so you have to remove it before parsing it.
Here is a working example.
// Code goes here
$(function () {
$.getJSON("https://api.myjson.com/bins/89vsf", function (jsonFromFile) {
$('#table1').bootstrapTable({
data: jsonFromFile.rows
})
var data = $('#table1').bootstrapTable('getData');
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue.replace('$',''));
}, 0);
document.querySelector('.total1').innerHTML = total1;
});
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="table1">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Account">Account #</th>
<th data-field="ClientName">Client</th>
<th data-field="AccountType">Account Type</th>
<th data-field="LongMarketValue"> Market Value</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<th></th>
<th> Total <span class="total1"></span></th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.js"></script>
<script src="script.js"></script>
</body>
</html>
Here is a working plunker of the code. http://plnkr.co/edit/PSCR5iS7DSWkuQb1jv5P?p=preview
Hope this helps.

Related

HTML/Javascript - Tables

Good day,
I want a straightforward way to loop through data and display it in a table.
If there's more data then it must create more rows etc.
Columns are fixed.. for now.
Example the code looks like the following
<table>
<thead>
<tr>
<th>Client Name</th>
<th>Client Representative</th>
<th>Client Representative Position</th>
<th>Client Representative Email</th>
<th>Date Created</th>
</tr>
</thead>
<tbody>
<tr>
<td id="client_name"></td>
<td id="client_representative"> </td>
<td id="client_representative_position"> </td>
<td id="client_representative_email"></td>
<td id="date_created"></td>
</tr>
</tbody>
</table>
<script>
var data = {
client_name: "Example Company",
client_representative: "John",
client_representative_position: "Engineer",
client_representative_email: "John#example.com",
date_created: "25/02/2021",
} **
document.getElementById("client_name").innerHTML = data.client_name;
document.getElementById("client_representative").innerHTML = data.client_representative;
document.getElementById("client_representative_position").innerHTML = data.client_representative_position;
document.getElementById("client_representative_email").innerHTML = data.client_representative_email;
document.getElementById("date_created").innerHTML = data.date_created; **
</script>
Basically, I want to avoid that piece surrounded by ** (javascript) bit by having it loop through the data.
Thanks in advance!
You Can use jQuery append()
Try this
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body>
<table >
<thead >
<tr>
<th>Client Name</th>
<th>Client Representative</th>
<th>Client Representative Position</th>
<th>Client Representative Email</th>
<th>Date Created</th>
</tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
</body>
<script>
var data = [ {
client_name : "Example Company",
client_representative:"John",
client_representative_position:"Engineer",
client_representative_email:"John#example.com",
date_created:"25/02/2021",
},
{
client_name : "Example Company 2",
client_representative:"John 2",
client_representative_position:"Engineer 2",
client_representative_email:"John2#example.com",
date_created:"5/02/2021",
},
]
for (let index = 0; index < data.length; index++) {
var html = "<tr>";
html +="<td>"+data[index].client_name+"</td>";
html +="<td>"+data[index].client_representative+"</td>";
html +="<td>"+data[index].client_representative_position+"</td>";
html +="<td>"+data[index].client_representative_email+"</td>";
html +="<td>"+data[index].date_created+"</td>";
html += "</tr>";
$('#table-body').append(html);
}
</script>
</html>
To get the names of the keys in an object, you can use the in keyword.
This just loops through the keys as strings, allowing you to use in to set the elements in the table.
for (key in data)
document.getElementById(key).innerHTML = data[key]

Update the chart data from an array stored in a variable on button click

I have a chart that gets the data values from a table column. It currently works on its own, but I want to add a functionality that changes/updates the data of the chart on button click. I tried this code but it doesn't work (arrays are very confusing for me):
var canvasP = document.getElementById("pieChart");
var table = document.getElementById("myTable");
var nameArr = [];
var data1Arr = [];
var data2Arr = [];
var tableLen = table.rows.length;
var i;
for (i = 1; i < tableLen; i++) {
nameArr.push(table.rows[i].cells[0].textContent);
data1Arr.push(table.rows[i].cells[1].innerHTML);
data2Arr.push(table.rows[i].cells[2].innerHTML);
}
nameArr.pop();
data1Arr.pop();
data2Arr.pop();
var ctxP = canvasP.getContext("2d");
var myPieChart = new Chart(ctxP, {
type: "pie",
data: {
labels: nameArr,
datasets: [{
data: data1Arr,
backgroundColor: ["#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1", "#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1"],
label: "Data"
}]
},
options: {
legend: {
display: true,
position: "right"
},
title: {
display: true,
text: "Data 1"
}
}
});
// the button functions below do not work. I am trying to load the array variables into the data:
document.getElementById("btn1").addEventListener("click", function() {
myPieChart.data.datasets.data = data1Arr;
});
document.getElementById("btn2").addEventListener("click", function() {
myPieChart.data.datasets.data = data2Arr;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<table id='myTable'>
<thead>
<tr>
<th>Name</th>
<th>1st data</th>
<th>2nd data</th>
</tr>
</thead>
<tbody>
<tr>
<th>Item 1</th>
<td>337</td>
<td>411</td>
</tr>
<tr>
<th>Item 2</th>
<td>290</td>
<td>110</td>
</tr>
<tr>
<th>Item 3</th>
<td>197</td>
<td>800</td>
</tr>
<tr>
<th>Item 4</th>
<td>765</td>
<td>211</td>
</tr>
<tr>
<th>Item 5</th>
<td>331</td>
<td>451</td>
</tr>
<tr>
<th>Item 6</th>
<td>957</td>
<td>871</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total</th>
<td id='curPop'>2877</td>
<td>2854</td>
</tr>
</tfoot>
</table>
<canvas id='pieChart'></canvas>
<button id="btn1">
Data 1
</button>
<button id="btn2">
Data 2
</button>
What I would want is that when the Data 2 button is clicked, it loads the appropriate data from the table (2nd data) into the pie chart, and that the Data 1 button loads the 1st data of the table.
After testing several times, this seems to fix the issue:
document.getElementById("btn1").addEventListener("click",function(){
myPieChart.data.datasets[0].data = data1Arr;
myPieChart.update();
});
document.getElementById("btn2").addEventListener("click",function(){
myPieChart.data.datasets[0].data = data2Arr;
myPieChart.update();
});

How to access additional data in JSON requested by Dynatable AJAX call

I am using the dynatable.com plugin to create a table of of schools that are stored in our database. The table can be filtered so does not always show the total number of schools. We do not display a 'number of pupils' column but are trying to show a 'total number of pupils' summary at the bottom of the table.
html on the page is as follows:
<table id="dynatable">
<thead>
<tr>
<th data-dynatable-column="id">ID</th>
<th data-dynatable-column="schoolName">School Name</th>
<th data-dynatable-column="contactName">Contact Name</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="3"><span id="numPupils"></span> Pupils</td>
</tr>
</tfoot>
</table>
Followed by the JS:
<script>
$('#dynatable').dynatable({
dataset: {
ajax: true,
ajaxUrl: '/my/json/page.json',
ajaxOnLoad: true,
records: []
}
});
</script>
And a sample of the JSON retrieved (note the additional totalNumPupils field at the bottom):
{
"records": [
{
"id": "1",
"schoolName": "ABC School",
"contactName": "Terry"
},
{
"id": "17",
"schoolName": "DEF School",
"contactName": "Claire"
},
{
"id": "45",
"schoolName": "GHI School",
"contactName": "Barry"
}
],
"queryRecordCount": 3,
"totalRecordCount": 450,
"totalNumPupils": 794
}
I am trying to establish if there is a way to access the responseJSON.totalNumPupils that is requested by dynatable's ajax call or whether I would have to perform my own ajax call, ascertain the number of pupils, then pass in the JSON to the dynatable function afterwards?
Please see the code snippet. You can use normal AJAX to get the JSON payload, then populate the dynatable with the data from the AJAX response, while simultaneously accessing the unique totalNumPupils property.
$('#dynatable').dynatable({
dataset: {
ajax: true,
ajaxUrl: 'https://api.myjson.com/bins/1ezw8l',
ajaxOnLoad: true,
records: []
}
});
$.ajax({
url: 'https://api.myjson.com/bins/1ezw8l',
success: function(data) {
$('#dynatable').dynatable({
dataset: {
ajax: false,
records: data
}
});
$('#numPupils').text("Total Pupils: " + data.totalNumPupils);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.css" rel="stylesheet" />
<table id="dynatable">
<thead>
<tr>
<th data-dynatable-column="id">ID</th>
<th data-dynatable-column="schoolName">School Name</th>
<th data-dynatable-column="contactName">Contact Name</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="3"><span id="numPupils"></span> Pupils</td>
</tr>
</tfoot>
</table>

Generating diff view using ng-repeat

I have a json containing revision/history info of modified entity which holds its old and new values. Diff is generated with https://github.com/benjamine/jsondiffpatch and I've done additional parsing myself to form final json format to be rendered.
Example data:
[
{
"createdBy": "admin#localhost",
"modifiedAt": 1445113889873,
"left": [
{
"Status": "Open"
}
],
"right": [
{
"Status": "In Progress"
}
]
},
{
"createdBy": "admin#localhost",
"modifiedAt": 1445114315786,
"left": [
{
"Description": "hello"
},
{
"Assignee": "Uncle Bob (test#test)"
}
],
"right": [
{
"Description": "bye"
},
{
"Assignee": "Willy Wonka (willy#hello)"
}
]
}
]
I am looking a nice way to form a table for this where for each revision I get separately left and right columns and values on separate rows. Probably tired, but I can't figure out how would ng-repeat work for this:
<div ng-repeat="(key, value) in vm.revisions | orderBy:'-modifiedAt'">
<table class="table">
<thead>
<tr>
<th width="20%">Field</th>
<th width="40%">Old Value</th>
<th width="40%">New Value</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
I am hoping for result like this:
Thanks in advance!
If I am right about data format:
<div ng-repeat="revision in vm.revisions | orderBy:'-modifiedAt'">
<table class="table">
<thead>
<tr>
<th width="20%">Field</th>
<th width="40%">Old Value</th>
<th width="40%">New Value</th>
</tr>
</thead>
<tbody ng-repeat="(index, left) in revision.left">
<tr ng-repeat="(field, leftValue) in left">
<td>{{field}}</td>
<td>{{leftValue}}</td>
<td>{{revision.right[index][field]}}</td>
</tr>
</tbody>
</table>
</div>
See it on jsfiddle: http://jsfiddle.net/q6zqgfr8/

Create table using Mushtache.js

I am facing a problem while creating a table using Mushtache.js
View file:
<table class="table table-bordered table-hover table-striped tablesorter">
<thead>
<tr>
<th class="header">Name</th>
<th class="header">Email ID</th>
<th class="header">Contact Number</th>
<th class="header">Edit</th>
</tr>
</thead>
<tbody>
<div id="eTableList"></div>
<script id="eList" type="text/template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
<td>{{contact_number}}</td>
<td>View/Edit</td>
</tr>
</script>
</tbody>
</table>
JS code:
function createTable(jsonEData){
var template = $("#eList").html();
expList = Mustache.render(template, jsonEData);
$("#expertTableList").html(expList);
}
I am calling this method as
<script language="javascript">
$(document).ready(function(){
createTable(<?php echo $this->eList;?>);
})
</script>
and the value of $this->eList = jsonEData is
[
{
"id": "52d3d523bdde226f17a581ba",
"name": "shgajsah",
"email": "0",
"contact_number": 2147483647
},
{
"id": "52d3d5c8bdde22c817a581ba",
"name": "fffsdf",
"email": "asa#ddjdj.com",
"contact_number": 323323232
}
]
I am not getting any error but table is not getting populated using above code. So please tell me where I am doing wrong?
You're not iterating over your items, give this a shot:
{{#.}}
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
<td>{{contact_number}}</td>
<td>View/Edit</td>
</tr>
{{/.}}
or perhaps:
{{#each .}}
<tr> ... </tr>
{{/each .}}

Categories