Javascript calling API array handling with HTML - javascript

I am calling a BUS ETA api which it will return a json with ETA and route information. Example as below. I manage to get the first array to show in HTML but without success for the second [1] and third[2]. I manage to see all three ETA with console.log but won't show in HTML.
Any idea?
UPDATE : Created a jsFiddle example.
https://jsfiddle.net/21tk38b9/
BUS ETA API SAMPLE DATA
{
"type": "ETA",
"version": "1.0",
"generated_timestamp": "2021-06-29T16:02:53+08:00",
"data": [
{
"co": "KMB",
"route": "978",
"dir": "I",
"service_type": 1,
"seq": 7,
"dest_tc": "粉嶺(華明)",
"dest_sc": "粉岭(华明)",
"dest_en": "FANLING (WAH MING)",
"eta_seq": 1,
"eta": "2021-06-29T16:11:24+08:00",
"rmk_tc": "",
"rmk_sc": "",
"rmk_en": "",
"data_timestamp": "2021-06-29T16:02:41+08:00"
},
{
"co": "KMB",
"route": "978",
"dir": "I",
"service_type": 1,
"seq": 7,
"dest_tc": "粉嶺(華明)",
"dest_sc": "粉岭(华明)",
"dest_en": "FANLING (WAH MING)",
"eta_seq": 2,
"eta": "2021-06-29T16:28:15+08:00",
"rmk_tc": "原定班次",
"rmk_sc": "原定班次",
"rmk_en": "Scheduled Bus",
"data_timestamp": "2021-06-29T16:02:41+08:00"
},
{
"co": "KMB",
"route": "978",
"dir": "I",
"service_type": 1,
"seq": 7,
"dest_tc": "粉嶺(華明)",
"dest_sc": "粉岭(华明)",
"dest_en": "FANLING (WAH MING)",
"eta_seq": 3,
"eta": "2021-06-29T16:43:15+08:00",
"rmk_tc": "原定班次",
"rmk_sc": "原定班次",
"rmk_en": "Scheduled Bus",
"data_timestamp": "2021-06-29T16:02:41+08:00"
}
]
}
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mining Status</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/src/js/Untitled-4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="/src/css/main.css">
<link rel="stylesheet" href="/src/css/15.css">
<style type="text/css">
.fullscreen {
position: fixed;
overflow-y:fixed;
width: 100%;
}
</style>
</head>
<div id="wrap">
<body>
<div style="
font-size: 100px;
text-align: center;">
<div id="rmk"></div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Route</th>
<th scope="col">ETA</th>
<th scope="col">Remark</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><div id="route"></div></td>
<td><div id="but"></div>
</td>
<td></td>
</tr>
<tr>
<th scope="row">2</th>
<td></td>
<td><div id="but"></div>
<td></td>
</tr>
<tr>
<th scope="row">3</th>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</body>
</div>
</html>
Javascript
function repeat57() {
$(function() {
$.ajax({
type: "GET",
url: "https://data.etabus.gov.hk/v1/transport/kmb/eta/83B717529F9794BC/978/1",
dataType: "json",
success: function (data) {
console.log(typeof data); // -- Object
var json = data;
for (var i = 0; i < json.data.length; i++) {
var str = json.data[i].eta
if (str !== null ) {
str = str.split("T").pop();
str2 = str.split("+",1).pop();
str3 = str2.replace(/:/g,'');
d = new Date();
datetext = d.toTimeString();
datetext = datetext.split(' ')[0];
datetext = datetext.replace(/:/g,'');
console.log(datetext)
var eta = str3 - datetext;
console.log(eta)
var eta2 = "[ " + eta.toString().slice(0, -2) +" mins,]";
} else {
var remark = json.data[i].rmk_tc
eta2 = remark;
}
console.log(typeof str)
$('#but').html(eta2);
$('#rmk').html(remark);
}
}
});
});
setTimeout(repeat57, 19000);
}
repeat57();
function repeat58() {
$(function() {
$.ajax({
type: "GET",
url: "https://data.etabus.gov.hk/v1/transport/kmb/eta/83B717529F9794BC/978/1",
dataType: "json",
success: function (data) {
var json = data;
console.log(typeof .json)
for (var i = 0; i < json.data.length; i++) {
var str = JSON.parse(json.data[i].route)
if (str !== null ) {
} else {
var remark = json.data[i].rmk_tc
str = remark;
}
console.log(typeof str)
$('#route').html(str);
}
}
});
});
setTimeout(repeat58, 19000);
}
repeat58();

Do you want to be dynamic or are there always only 3 entries?
If there are three entries you could do:
HTML Code:
<head>
<meta charset="utf-8">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="rmk"></div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Route</th>
<th scope="col">ETA</th>
<th scope="col">Remark</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>
<div class="route"></div>
</td>
<td>
<div class="but"></div>
</td>
<td></td>
</tr>
<tr>
<th scope="row">2</th>
<td>
<div class="route"></div>
</td>
<td>
<div class="but"></div>
</td>
<td></td>
</tr>
<tr>
<th scope="row">3</th>
<td>
<div class="route"></div>
</td>
<td>
<div class="but"></div>
</td>
<td></td>
</tr>
</tbody>
</table>
</body>
JavaScript:
function repeat57() {
$(function() {
$.ajax({
type: "GET",
url: "https://data.etabus.gov.hk/v1/transport/kmb/eta/83B717529F9794BC/978/1",
dataType: "json",
success: function(data) {
console.log(data); // -- Object
var json = data;
const buts = $('.but');
for (var i = 0; i < json.data.length; i++) {
var str = json.data[i].eta
if (str !== null) {
str = str.split("T").pop();
str2 = str.split("+", 1).pop();
str3 = str2.replace(/:/g, '');
d = new Date();
datetext = d.toTimeString();
datetext = datetext.split(' ')[0];
datetext = datetext.replace(/:/g, '');
console.log(datetext)
var eta = str3 - datetext;
var eta2 = eta.toString().slice(0, -2) + " mins";
} else {
var remark = json.data[i].rmk_tc
eta2 = remark;
}
$(buts[i]).html(eta2);
}
}
});
});
setTimeout(repeat57, 19000);
}
repeat57();
function repeat58() {
$(function() {
$.ajax({
type: "GET",
url: "https://data.etabus.gov.hk/v1/transport/kmb/eta/83B717529F9794BC/978/1",
dataType: "json",
success: function(data) {
var json = data;
console.log(json)
const routeElements = $('.route');
for (var i = 0; i < json.data.length; i++) {
var str = JSON.parse(json.data[i].route)
if (str !== null) {
} else {
var remark = json.data[i].rmk_tc
str = remark;
}
$(routeElements[i]).html(str);
}
}
});
});
setTimeout(repeat58, 19000);
}
repeat58();
Make sure to change the ids to classes (but, route, etc) and add it to all the rows where it is needed.
And when iterating through the result you pick the correct element via the index.
See the updated jsFiddle: https://jsfiddle.net/sgjx05qf/
This would be a solution if you always know the count of the result.

Related

Datatables ExcelHTMl5 export add Page-Header and Page-Footer

How can I add page_header and page_footer sections in the exported excel file from datatables so that the header and footer will be in each page while printing the document?
Current Printing view of the exported excel without page_header, page_footer:
Printing view I want with page_header, page_footer:
Here is my sample code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.5/css/buttons.dataTables.css"/>
</head>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start<br />date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger<br />Nixon</td>
<td>System<br />Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett<br />Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton<br />Cox</td>
<td>Junior<br />Technical<br />Author</td>
<td>San<br />Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric<br />Kelly</td>
<td>Senior<br />Javascript<br />Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi<br />Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start<br />date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.5/js/dataTables.buttons.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.5/js/buttons.html5.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable({
dom: "Bftrip",
buttons: [
{
extend: 'excelHtml5',
messageTop : 'Employee List',
footer: true,
exportOptions: {
format: {
header: function ( data, row, column, node ) {
return data.replace(/<br\s*\/?>/ig, "\r\n");
},
body: function ( data, row, column, node ) {
return data.replace(/<br\s*\/?>/ig, "\r\n");
},
footer: function ( data, row, column, node ) {
return data.replace(/<br\s*\/?>/ig, "\r\n");
}
},
},
customize: function(xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
var sSh = xlsx.xl['styles.xml'];
var lastXfIndex = $('cellXfs xf', sSh).length - 1;
var newStyleNumber = lastXfIndex + 1;
var newStyleNumber2 = lastXfIndex + 2;
var currentDoc = "";
var currentStyle;
var s1 = '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment vertical="center" horizontal="center" wrapText="1"/></xf>';
var s2 = '<xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment vertical="center" horizontal="center" wrapText="1"/></xf>';
sSh.childNodes[0].childNodes[5].innerHTML += s1+ s2;
var rowCount = document.getElementById("example").rows.length + 1;
for(var i=0; i<3; i++) {
$('row:eq(' + i + ') c*', sheet).attr('s', newStyleNumber2);
}
for(var i=3; i<rowCount; i++) {
$('row:eq(' + i + ') c*', sheet).attr('s', newStyleNumber);
}
$('row:eq(' + i + ') c*', sheet).attr('s', newStyleNumber2);
var col = $('col', sheet);
$(col[0]).attr('width', 15);
$(col[1]).attr('width', 15);
$(col[2]).attr('width', 10);
$(col[3]).attr('width', 5);
$(col[4]).attr('width', 12);
$(col[5]).attr('width', 12);
}
}
]
});
});
</script>
</body>
</html>
With this code, you can create a header and footer page.
"buttons": [
{
extend: 'excelHtml5',
text: 'Excel',
customize: function( xlsx ) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
// Get reference to the worksheet and parse it to xml nodes
// Has to be done this way to avoid creation of namespace atributes.
var afSerializer = new XMLSerializer();
var xmlString = afSerializer.serializeToString(sheet);
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString,'text/xml');
//Create header and add it to the worksheet
var headerFooter = xmlDoc.createElementNS('http://schemas.openxmlformats.org/spreadsheetml/2006/main','headerFooter');
sheet.getElementsByTagName('worksheet')[0].appendChild(headerFooter);
var nodeHeaderFooter = sheet.getElementsByTagName("headerFooter");
//Creation of the header
var oddHeader = xmlDoc.createElementNS('http://schemas.openxmlformats.org/spreadsheetml/2006/main','oddHeader');
nodeHeaderFooter[0].appendChild(oddHeader);
var nodeOddHeader = sheet.getElementsByTagName("oddHeader");
//The header/footer column definitions
// If unwanted, you can skip a column
//&L = Left column
//&F = Filename
//&A = sheetname
//&C = Center column
//&D = Date
//&T = Time
//&R = Right Column
//&P = Pagenumber
//&N = Total number of pages
var txtHeader = "&L"+"&F - &A"+"&R"+"&D - &T";
var nodeHeader = xmlDoc.createTextNode(txtHeader);
nodeOddHeader[0].appendChild(nodeHeader);
//Creation of the footer
var oddFooter = xmlDoc.createElementNS('http://schemas.openxmlformats.org/spreadsheetml/2006/main','oddFooter');
nodeHeaderFooter[0].appendChild(oddFooter);
var nodeOddFooter = sheet.getElementsByTagName("oddFooter");
var txtFooter = "&R"+"Page &P of &N";
var nodeFooter = xmlDoc.createTextNode(txtFooter);
nodeOddFooter[0].appendChild(nodeFooter);
//Add header and footer to the worksheet
sheet.getElementsByTagName('worksheet')[0].appendChild(headerFooter);
}
}
]
I found the solution at this link https://codepen.io/RedJokingInn/pen/yMqezX

How to call a javascript method with knockout

I am using knockout for binding, and the issue I have is can't seem to know how to call the remove method. I have two class convocation, and vague.
class Convocation {
constructor(sessionId, description)
{
var self = this;
this.ConvocationID = ko.observable(sessionId);
this.ConvDesc = ko.observable(description);
this.Vagues = ko.observableArray();
addVague(start, end) {
this.Vagues.push(new Vague(start, end));
}
removeVague() {
self.Vagues.remove(this)
}
}
class Vague {
constructor(start, end) {
this.startDate = ko.observable(start);
this.endDate = ko.observable(end);
}
}
I initialize my knockout using this viewModel, witch works.
function ViewModel() {
var self = this;
this.Convocations = ko.observableArray();
// Get information
this.Initialize = function () {
$.ajax({
url: "/Convocations/GetConvocationList",
dataType: 'json',
//data: { id: id },
success: function (data) {
for (var i = 0; i < data.length; i++) {
self.Convocations.push(new Convocation(data[i].sessionCode, data[i].desc));
for (var j = 0; j < data[i].vagues.length; j++) {
self.Convocations()[i].addVague(data[i].vagues[j].start, data[i].vagues[j].end);
}
}
}
});
}
}
This is my jquery calling the viewModel once ready.
(function ($) {
// we can now rely on $ within the safety of our "bodyguard" function
$(document).ready(function () {
var vm = new ViewModel();
ko.applyBindings(vm);
vm.Initialize();
});
})(jQuery);
But when it comes to delete a vague, I can't seem to know how to call it this is a snip of my view
<tbody data-bind="foreach: Convocations">
<tr>
<td><Input data-bind="value: $data.ConvocationID"></td>
<td><Input data-bind="value: $data.ConvDesc"></td>
</tr>
<tr>
<td colspan="3">
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Start Date</th>
<th>End Date</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: $data.Vagues">
<tr>
<td><span type="date" data-bind="text: $data.startDate"></span></td>
<td><span type="date" data-bind="text: $data.endDate"></span></td>
<td><a href='#' data-bind='click: $parent.removeVague'>Delete</a></td>
</tr>
</tbody>
</table>
If i conver addRemove() to something like this, it use to work, but i can't define this in a class.
this.remove = function () {
self.Vagues.remove(this);
}
I suspect that there may be some confusion around what $data and $parent represents in the html bindings.
for the nested foreach knockout bindings like you have its generally a good idea to give each level its own object name rather than just using $data.
Personally I am still learning the javascript syntax around classes etc, so there is probably a better way of doing the javascript than what I have done.
var data = [{
sessionCode: 1,
desc: 'Convocation 1',
vagues: [{
start: '2020-07-01',
end: '2020-07-30'
}]
}, {
sessionCode: 2,
desc: 'Convocation 2',
vagues: [{
start: '2020-07-02',
end: '2020-07-29'
}]
}];
class Convocation {
constructor(sessionId, description) {
var self = this;
self.ConvocationID = ko.observable(sessionId);
self.ConvDesc = ko.observable(description);
self.Vagues = ko.observableArray();
self.addVague = function addVague(start, end) {
self.Vagues.push(new Vague(start, end));
}
self.removeVague = function removeVague(item) {
self.Vagues.remove(item);
}
}
}
class Vague {
constructor(start, end) {
this.startDate = ko.observable(start);
this.endDate = ko.observable(end);
}
}
function ViewModel() {
var self = this;
self.Convocations = ko.observableArray();
//helper function that mimics the success function of the ajax call to allow loading data
self.processData = function(data) {
for (var i = 0; i < data.length; i++) {
self.Convocations.push(new Convocation(data[i].sessionCode, data[i].desc));
for (var j = 0; j < data[i].vagues.length; j++) {
self.Convocations()[i].addVague(data[i].vagues[j].start, data[i].vagues[j].end);
}
}
}
// Get information
self.Initialize = function() {
$.ajax({
url: "/Convocations/GetConvocationList",
dataType: 'json',
//data: { id: id },
success: function(data) {
for (var i = 0; i < data.length; i++) {
self.Convocations.push(new Convocation(data[i].sessionCode, data[i].desc));
for (var j = 0; j < data[i].vagues.length; j++) {
self.Convocations()[i].addVague(data[i].vagues[j].start, data[i].vagues[j].end);
}
}
}
});
}
}
var vm = new ViewModel();
ko.applyBindings(vm);
//vm.Initialize();
vm.processData(data);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table class="table">
<tbody data-bind="foreach: {data: Convocations, as: 'convocation'}">
<tr>
<td>
<input data-bind="value: convocation.ConvocationID" />
</td>
<td>
<input data-bind="value: convocation.ConvDesc" />
</td>
</tr>
<tr>
<td colspan="3">
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Start Date</th>
<th>End Date</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach:{data: convocation.Vagues, as: 'vague'}">
<tr>
<td><span type="date" data-bind="text: vague.startDate"></span></td>
<td><span type="date" data-bind="text: vague.endDate"></span></td>
<td><a href='#' data-bind='click: convocation.removeVague'>Delete</a></td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</table>

replace the table data with the selected data(javascript)

javascript beginner here, trying to code and learn.
I have a table filled with data (fetch from url) and that data is
{
"france": "paris",
"finland": "helsinki",
"sweden": "stockholm",
"tajikistan": "dushanbe",
"uzbekistan ": "toshkent",
"china": "peking",
"dole": {
"Key": "fhd699f"
}
}
and under the table I have a select box (the data of it also fetched from url) its data is this
[
{"nimi": "tili","id": "48385","somewhere": "nassau","somewhere2": "bamako","somewhere3": "rabat","somewhere4": "baku"},
{"nimi": "tili","id": "789642","somewhere": "windhoek","somewhere2": "podgorica","somewhere3": "niamey","somewhere4": "islamabad"}
]
i want to replace the table data with the selected data ( i mean everything) even table's <th> also, for example table's <th> is 'france' and value is 'paris' but after replace table's <th> should be 'nimi' and value 'tili' according to select box data.
here is my code (as you can see 'tajikistan','uzbekistan','china' for some reason not going to their places in table):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<style>
</style>
</head>
<body>
<div class="container">
<table class="table ">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
<tbody id="tiedot2">
</tbody>
</table>
<select id="valittu" name="name"></select>
</div>
<script>
fetch(
"https://tdejdjd***",
{
method: "GET",
headers: {
"x-api-key": "i****y"
}
}
)
.then((res) => {
res
.json()
.then((data) => {
tableupdating(data, ['france','finland','sweden','tajikistan','uzbekistan','china']);
})
.catch((err) => {
console.log("ERROR: " + err);
});
});
function tableupdating(data, values) {
const totable = document.getElementById("tiedot");
const totable2 = document.getElementById("tiedot2");
totable.innerHTML = "";
totable2.innerHTML = "";
var komb = "";
var komb2 = "";
komb += "<tr>";
komb2 += "<tr>";
values.forEach(value => {
komb += "<td>" + data[value] + "</td>";
})
values.forEach(value => {
komb2 += "<td>" + data[value] + "</td>";
})
totable.insertAdjacentHTML("beforeend", komb);
totable2.insertAdjacentHTML("beforeend", komb2);
}
let dataArray;
fetch(
"https://tdejdjd***",
{
method: "GET",
headers: {
"x-api-key": "i****y"
}
}
)
.then((res) => {
res.json().then((data) => {
dataArray = data;
updateSelect(data, ['nimi','id']);
});
});
function updateSelect(data, values) {
for (var i = 0; i < data.length; i++) {
var Valittu = document.getElementById("valittu");
var option = document.createElement("option");
values.forEach(value => {
option.textContent += data[i][value] + ' '
})
Valittu.appendChild(option);
}
}
document.getElementById("valittu").addEventListener("change", function (event) {
const chosenID = event.target.value.split(" ")[1];
const chosenData = dataArray.filter((data) => data.id === chosenID)[0];
tableupdating(chosenData, ['nimi', 'id', 'somewhere','somewhere2','somewhere3','somewhere4']);
});
</script>
</body>
</html>
as spoken in chat, here is new code, it is working but for some reason these three are in same line and not on their places : komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";
code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<style>
</style>
</head>
<body onload="fillTheBox();">
<div class="container">
<table class="table" id="myTable">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
</table>
<select id="valittu" name="name" onchange="changed()"></select>
</div>
<script>
fetch("https://qj",
{
method: "GET",
headers: {
"x-api-key": ""
}
}
).then(res =>{
res.json().then(tiedot => {
console.log(tiedot);
var komb ="";
komb +="<tr>";
komb += "<td>"+tiedot.france+"</td>";
komb += "<td>"+tiedot.finland+"</td>";
komb += "<td>"+tiedot.sweden+"</td>";
komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";
document.getElementById("tiedot").insertAdjacentHTML("beforeend", komb );
}
)
})
var dataArray = [
{ "nimi": "tili", "id": "48385", "somewhere": "nassau", "somewhere2": "bamako", "somewhere3": "rabat", "somewhere4": "baku" },
{ "nimi": "tili", "id": "789642", "somewhere": "windhoek", "somewhere2": "podgorica", "somewhere3": "niamey", "somewhere4": "islamabad" }
]
function fillTheBox() {
var selectBox = document.getElementById("valittu");
var option = document.createElement("option");
option.value = dataArray[0];
option.text = dataArray[0].nimi+' '+dataArray[0].id;
selectBox.add(option);
var option1 = document.createElement("option");
option1.value = dataArray[1];
option1.text = dataArray[1].id;
selectBox.add(option1);
}
function changed() {
var e = document.getElementById("valittu");
var selectedObjectID = e.options[e.selectedIndex].text;
chosenData = dataArray.filter((data) => data.id === selectedObjectID)[0];
var myTable = document.getElementById("myTable");
myTable.innerHTML = "";
generateTable(myTable, chosenData);
}
function generateTable(table, data) {
let row1 = table.insertRow();
row1.className = "table-success";
let row2 = table.insertRow();
let row3 = table.insertRow();
row3.className = "table-success";
let row4 = table.insertRow();
var counter = 1;
for (key in data) {
if (counter<=3) {
let cell = row1.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row2.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
} else {
let cell = row3.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row4.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
}
counter++;
}
}
</script>
</body>
</html>
I created a basic demo to show the logic. Firs of all give an id to your table. And create a onChange event for your select box. In your event function edit your table content with innerHTML property. Just focus on change() and generateTable() functions in my code
<body onload="fillTheBox();">
<div class="container">
<table class="table" id="myTable">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
</table>
<select id="valittu" name="name" onchange="changed()"></select>
</div>
<script>
var dataArray = [
{ "nimi": "tili", "id": "48385", "somewhere": "nassau", "somewhere2": "bamako", "somewhere3": "rabat", "somewhere4": "baku" },
{ "nimi": "tili", "id": "789642", "somewhere": "windhoek", "somewhere2": "podgorica", "somewhere3": "niamey", "somewhere4": "islamabad" }
]
function fillTheBox() {
var selectBox = document.getElementById("valittu");
var option = document.createElement("option");
option.value = dataArray[0];
option.text = dataArray[0].id;
selectBox.add(option);
var option1 = document.createElement("option");
option1.value = dataArray[1];
option1.text = dataArray[1].id;
selectBox.add(option1);
}
function changed() {
var e = document.getElementById("valittu");
var selectedObjectID = e.options[e.selectedIndex].text;
chosenData = dataArray.filter((data) => data.id === selectedObjectID)[0];
var myTable = document.getElementById("myTable");
myTable.innerHTML = "";
generateTable(myTable, chosenData);
}
function generateTable(table, data) {
let row1 = table.insertRow();
row1.className = "table-success";
let row2 = table.insertRow();
row2.className = "table-success";
let row3 = table.insertRow();
row3.className = "table-success";
let row4 = table.insertRow();
row4.className = "table-success";
var counter = 1;
for (key in data) {
if (counter<=3) {
let cell = row1.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row2.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
} else {
let cell = row3.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row4.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
}
counter++;
}
}
</script>
</body>
</html>
UPDATE:
To separate the fields mentioned in question add a <tr> element between them.
komb +="<tr>";
komb += "<td>"+tiedot.france+"</td>";
komb += "<td>"+tiedot.finland+"</td>";
komb += "<td>"+tiedot.sweden+"</td>";
komb +="</tr><tr>";
komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";

Tablesorter is not working with the table

TableThis is my cshtml and js codes. I tried tablesorter plugin on other tables (justnormal tables with thead and tbody) and it was working. I think the problem is that there is no body inside of tbody tags because I add the body with JS and webapi , do you have any idea how can I fix it and sort this table? I am a beginner, so would appreciate any help or advice.
<head>
<script src="lib/jquery/dist/jquery.js" asp-append-version="true"></script>
<script src="js/jquery.tablesorter.min.js"></script>
<link rel="stylesheet" type="text/css" href="~/css/theme.default.css">
</head>
<h3>Branch Index</h3>
<div id="branchIndex">
<table class="table tablesorter mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp customTable" id="branchIndexTablee">
<thead>
<tr>
<th>Branch Name</th>
<th>Open Now</th>
<th>Number Of Assets</th>
<th>Number Of Patrons</th>
</tr>
</thead>
<tbody id="branchess">
</tbody>
</table>
</div>
<script>
$(document).ready(function () {
$('table').tablesorter({ sortList: [[0, 0]] });
});
</script>
js
const uri = 'api/BranchApi';
let branchess = [];
function getItems() {
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
}
function _displayItems(data) {
var table = jQuery(".tablesorter");
table.tablesorter();
const tBody = document.getElementById('branchess');
tBody.innerHTML = '';
data.forEach(item => {
let tr = tBody.insertRow();
let td1 = tr.insertCell(0);
var a = document.createElement('a');
var name = document.createTextNode(item.branchName);
a.appendChild(name);
a.title = item.name;
a.href = "Branch/Detail/" + item.id;
td1.appendChild(a);
let td2 = tr.insertCell(1);
let time = document.createTextNode(item.isOpen);
td2.append(time);
let td3 = tr.insertCell(2);
let telephoneN = document.createTextNode(item.numberOfAssets);
td3.appendChild(telephoneN);
let td4 = tr.insertCell(3);
let address = document.createTextNode(item.numberOfPatrons);
td4.appendChild(address);
});
branchess = data;
}
Typo: id has been assign to wrong place:
NOW:
<tbody >
<tr>
<td id="branchess"></td>
</tr>
</tbody>
Expected:
<tbody id="branchess">
<tr>
<td ></td>
</tr>
</tbody>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js"></script>
<link rel="stylesheet" type="text/css" href="~/css/theme.default.css">
</head>
<h3>Branch Index</h3>
<div id="branchIndex">
<table
class="table tablesorter mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp customTable"
id="branchIndexTablee">
<thead>
<tr>
<th>Branch Name</th>
<th>Open Now</th>
<th>Number Of Assets</th>
<th>Number Of Patrons</th>
</tr>
</thead>
<tbody id="branchess">
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
<script>
$(document).ready(function () {
_displayItems([{
id: 1,
branchName: "Random",
isOpen: true,
numberOfAssets: 10,
numberOfPatrons: 11
},
{
id: 2,
branchName: "Lost",
isOpen: true,
numberOfAssets: 10,
numberOfPatrons: 11
},
{
id: 3,
branchName: "Found",
isOpen: false,
numberOfAssets: 10,
numberOfPatrons: 11
},
{
id: 4,
branchName: "OK",
isOpen: true,
numberOfAssets: 10,
numberOfPatrons: 11
},
])
$('table').tablesorter({
sortList: [
[0, 0]
]
});
});
function _displayItems(data) {
const tBody = document.getElementById('branchess');
tBody.innerHTML = '';
data.forEach(item => {
let tr = tBody.insertRow();
let td1 = tr.insertCell(0);
var a = document.createElement('a');
var name = document.createTextNode(item.branchName);
a.appendChild(name);
a.title = item.name;
a.href = "Branch/Detail/" + item.id;
td1.appendChild(a);
let td2 = tr.insertCell(1);
let time = document.createTextNode(item.isOpen ? 'OPEN' : 'CLOSED');
td2.append(time);
let td3 = tr.insertCell(2);
let telephoneN = document.createTextNode(item.numberOfAssets);
td3.appendChild(telephoneN);
let td4 = tr.insertCell(3);
let address = document.createTextNode(item.numberOfPatrons);
td4.appendChild(address);
});
// branchess = data;
var table = jQuery(".tablesorter");
table.tablesorter();
}
</script>
</html>

Boostrap Table How to add commas between numbers

Hi Have the following code which populates bootstrap table.
During the table generation how do I format and add "$" before the number
and any number should be displayed in this order $100,00,00.00 or $100,00.00 or $100.00
here is my code
$(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;
});
});
HTML table
<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>
JSON
{
"Name": "Jie wn",
"Account": "C10",
"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": "06-1234",
"ClientName": "S Smth",
"AccountType": "tail",
"LongMarketValue": "$40000"
}, {
"Account": "08-1235",
"ClientName": "all Sth",
"AccountType": "REV Trust",
"LongMarketValue": "$55000"
},
{
"Account": "086-1236",
"ClientName": "Sly Smith",
"AccountType": "Reail",
"LongMarketValue": "$5500"
}]
}
You could use toLocaleString() to convert number to currency format. Or use regular expression to do this, How to print a number with commas as thousands separators in JavaScript
Working example.
$(function () {
$.getJSON("https://api.myjson.com/bins/89vsf", function (jsonFromFile) {
var rows = jsonFromFile.rows.map(function(item){
item.LongMarketValue = parseFloat(item.LongMarketValue.replace('$',''));
item.LongMarketValue = getFormattedCurrency(item.LongMarketValue);
return item;
});
$('#table1').bootstrapTable({
data: rows
})
var data = $('#table1').bootstrapTable('getData');
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue.replace('$','').split(',').join(''));
}, 0);
document.querySelector('.total1').innerHTML = getFormattedCurrency(total1);
});
});
function getFormattedCurrency(number){
return number.toLocaleString('en-US',{style: 'currency', currency: 'USD'});
}
<!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>
Working plunkr http://plnkr.co/edit/PSCR5iS7DSWkuQb1jv5P?p=preview
Hope this helps.
a couple of prototype functions that I use for this
String.prototype.toTwoDecimals = function () {
var value = this;
if (isNaN(value)) {
value = 0;
}
return parseFloat(Math.round(value * 100) / 100).toFixed(2);
};
String.prototype.toCommaSeperated = function () {
var value = this;
if (isNaN(value)) {
value = 0;
}
while (/(\d+)(\d{3})/.test(value.toString())) {
value = value.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return value;
};
String.prototype.toUSD = function () {
var value = this;
if (isNaN(value)) {
value = 0;
}
return '$' + this.toString().toTwoDecimals().toCommaSeperated();
};
then you can use "10000".toCommaSeperated() or "100000".toUSD()

Categories

Resources