DataTables dynamic cells won't render - javascript

I'm stuck with getting my datatable cells (column 'price') re-rendered based on drop-down value (currency). But as I select currency, nothing is happening with the table - all the figures just stay the same. Any ideas as of why render function fails to render?
My HTML+JavaScript is as follows:
var oldCurrency = 'usd';
var newCurrency = 'usd';
var myTable = $('#mytable').DataTable({
sDom: 't',
columns:[
{data: 'item', title: 'Item'},
{data: 'descr', title: 'Description'},
{data: 'cost', title: 'Cost', render: function(data, type, row){
var exchangeRate = {usd: 1, eur: 0.87, gbp: 0.78};
row.cost = row.cost*exchangeRate[newCurrency]/exchangeRate[oldCurrency];
return row.cost;
}}
]
});
$('#currency').on('focus', function(){
oldCurrency = this.value;
});
$('#currency').on('change', function(){
newCurrency = this.value;
myTable.draw();
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="test.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<select id="currency">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbp">GBP</option>
</select>
<table id="mytable">
<thead>
<th>Item</th>
<th>Description</th>
<th>Cost</th>
</thead>
<tbody>
<tr>
<td>pen</td>
<td>writing tool</td>
<td>5.5</td>
</tr>
<tr>
<td>pencil</td>
<td>wooden stick</td>
<td>4.8</td>
</tr>
<tr>
<td>eraser</td>
<td>piece of rubber</td>
<td>1.2</td>
</tr>
</tbody>
</table>
</body>
</html>

First off, I wouldn't do all the tedious HTML on your own - even if your data is static and you don't want all the features offered by ajax-sourced table, I'd rather use javascript source - I may guess, input data format would be closer to what you get from your SQL or MongoDB, or whatever backend storage you might use.
Next, I would split your model from the view in MVC terms and manipulate source data, rather then its visual representation. Even though your price data to certain extent always stays the same, DataTables might percieve those as different number figures. And thus, you may need to clean datatable contents and populate that with new figures.
So, your code with slight tweaks would look like:
var oldCurrency = 'usd';
var newCurrency = 'usd';
var tableData = [
{
item: 'pen',
descr: 'writing tool',
cost: 5.5
},
{
item: 'pencil',
descr: 'wooden stick',
cost: 3.75
},
{
item: 'eraser',
descr: 'piece of rubber',
cost: 1.2
},
];
var dataTable =
$('#mytable').DataTable({
sDom: 't',
data: tableData,
columns:[
{data: 'item', title: 'Item'},
{data: 'descr', title: 'Description'},
{data: 'cost', title: 'Cost', render: function(data, type, row){return row.cost.toPrecision(2)}}
]
});
$('#currency').on('focus', function(){
oldCurrency = this.value;
});
$('#currency').on('change', function(){
newCurrency = this.value;
let exchangeRate = {usd: 1, eur: 0.87, gbp: 0.78};
dataTable.clear();
$.each(tableData, function(){
let entry = JSON.parse(JSON.stringify(this));
entry.cost = this.cost*exchangeRate[newCurrency]/exchangeRate[oldCurrency];
dataTable.row.add(entry);
});
dataTable.draw();
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<select id="currency">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbp">GBP</option>
</select>
<table id="mytable"></table>
</body>
</html>

Related

Sort date field (moment js) in bootstrap-table

I have JSON data which I am rendering to a Bootstrap-Table (bootstrap-4). I want all the columns to be sortable. I am unable to sort the ISO date converted to moment.js format (MMM DD, YYYY). I am not able to sort the date based on header click. Is this possible?
var $table = $('#table')
$(function() {
var data = [
{
'dt': '2020-05-04T00:00:00.000Z',
'name': 'Item 1',
'price': '$1'
},
{
'dt': '2020-06-27T00:00:00.000Z',
'name': 'Item 2',
'price': '$2'
},
{
'dt': '2020-06-17T00:00:00.000Z',
'name': 'Item 3',
'price': '$3'
},
{
'dt': '2020-06-28T00:00:00.000Z',
'name': 'Item 4',
'price': '$4'
},
{
'dt': '2020-05-08T00:00:00.000Z',
'name': 'Item 5',
'price': '$5'
}
]
data.forEach(d=>{
d.dt = moment(d.dt).format('MMM DD, YYYY')
});
function datesSorter(a, b) {
if (new Date(a) < new Date(b)) return 1;
if (new Date(a) > new Date(b)) return -1;
return 0;
}
$table.bootstrapTable({data: data})
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link href="https://unpkg.com/bootstrap-table#1.17.1/dist/bootstrap-table.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/bootstrap-table#1.17.1/dist/bootstrap-table.min.js"></script>
<table id="table"
data-search="true">
<thead>
<tr>
<th data-field="dt" data-sortable="true" data-sorter="datesSorter">Date</th>
<th data-field="name">Item Name</th>
<th data-field="price">Item Price</th>
</tr>
</thead>
</table>
Is there something similar to the datatable version of $.fn.dataTable.moment? How to I sort dates using bootstrap-tables
Its pretty easy to solve your problem.
Use the sorter that you already have (but switch the < and >).
Then remove the date formatting part:
data.forEach(d=>{
dt = moment(d.dt).format('MMM DD, YYYY')
});
Now you can use a formatter to get the dateformat back.
function dateFormatter(date) {
return moment(date).format('MMM DD, YYYY')
}
(You have to use data-formatter="dateFormatter" on the Date column)
You can test it here.

Display the total value of a column below the table PHP

i've set up a table that fetches data from my database and display it on a web page. but i don't know how to get the total value of one of my columns and display it below the table
php code.
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['order_id'];
$sub_array[] = $row['order_customer_name'];
$sub_array[] = $row['order_item'];
$sub_array[] = $row['order_value'];
$sub_array[] = $row['order_date'];
$sub_array[] = $row['session'];
$sub_array[] = $row['total'];
$data[] = $sub_array;
}
Table:
div class="container box">
<table id="customer_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Order ID</th>
<th>Customer Name</th>
<th>Programs</th>
<th>Price</th>
<th>Date</th>
<th>Session</th>
<th>Total Price</th>
</tr>
</thead>
</table>
</div>
Javacript code (dataTable): in javascript, there is a code to filter data based on date and can export table data
<script type="text/javascript" language="javascript" >
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#customer_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
}
},
dom: 'lBfrtip',
buttons: [
'excel', 'csv', 'pdf', 'copy'
],
"lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ]
});
}
You can use Datatable column rendering options or other events to manipulate the data or calculating the total.
var globalDataSum=0;
var table =$('#example').DataTable( {
"columnDefs": [{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
globalDataSum+=data;
return data;
},
"targets": 0
}]
});
And listen to the data table drawn event. Then update the element
table.on( 'draw', function () {
$("#total").text(globalDataSum)
} );
If you want to use extensions of the data table to calculate the total, you can refer Data table Sum plugin

Pulling data from Quickbase for Highcharts.JS

Ok so I am trying to make a basic bar chart using highcharts and I am trying to use data that is contained in a QuickBase database, I have managed to pull the data from the server, I used an API call and have the data using this
http://pastebin.com/fJry1jA8
<!Doctype html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts.src.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts-more.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts-more.src.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/modules/exporting.src.js"></script>
<script>
var dbidApplication = "-EDITED OUT-";
var dbidTable = "-EDITED OUT-";
var apptoken = "-EDITED OUT-";
$.ajaxSetup({data: {apptoken: apptoken}});
var promise1 = $.get(dbidApplication , {
a: "dbpage",
pagename: "chart.html"
});
var promise2 = $.get(dbidTable, {
act: "API_GenResultsTable",
query: "{14.EX.'_FID_9}",
clist: "7.24.25.26.27.28.29.30.31.32.33.34.35.36.37",
jsa: 1,
options: "num-1",
});
$.when(promise1, promise2).then(function(chartArgs, dataArgs) {
var chart = chartArgs[0];
var markup = new Highcharts.Chart(chart, qdb_data);
console.log(markup);
});
</script>
<div id="container" style="width:100%; height:400px;"></div>
<script>
$(function () {
$('#container').highcharts({
chart: {
type: 'bar',
renderTo: 'container',
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
});
</script>
</body>
</html>
I've looked up examples of what people have told me, but now I am confused between being told I need to parse,pluck,get,and a list of other things that I have no clue what to look into so I can actually use this data, but I am looking for an explanation of whats actually going on also (I really don't find it helpful to see a bunch of code where half of it I don't understand because I haven't learned to that yet, its rather depressing)

Javascript Slickgrid, change row background on row select

I'm using slickgrid library, I have a grid that I would like it to have the ability of selecting a row on click and then chenge it's background color to red.
I'm using the code below, the grid click event is working I can print in the console the id of each row clicked but I don't know how to change the selected row background.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SlickGrid example 1: Basic grid</title>
<link rel="stylesheet" href="js/SlickGrid/slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="js/SlickGrid/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css"/>
<link rel="stylesheet" href="css/exemple.css" type="text/css"/>
</head>
<body>
<table width="100%">
<tr>
<td valign="top" width="50%">
<div id="myGrid" style="width:480px;height:187px;"></div>
</td>
</tr>
</table>
<script src="js/SlickGrid/lib/jquery-1.7.min.js"></script>
<script src="js/SlickGrid/lib/jquery.event.drag-2.2.js"></script>
<script src="js/SlickGrid/slick.core.js"></script>
<script src="js/SlickGrid/plugins/slick.rowselectionmodel.js"></script>
<script src="js/SlickGrid/slick.grid.js"></script>
<script>
var grid;
var columns = [
{id: "title", name: "Title", field: "title",selectable: true},
{id: "duration", name: "Duration", field: "duration"},
{id: "%", name: "% Complete", field: "percentComplete"},
{id: "start", name: "Start", field: "start"},
{id: "finish", name: "Finish", field: "finish"},
{id: "effort-driven", name: "Effort Driven", field: "effortDriven"}
];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
$(function () {
var data = [];
for (var i = 0; i < 5; i++) {
data[i] = {
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
}
grid = new Slick.Grid("#myGrid", data, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel());
grid.onClick.subscribe(function (e) {
var cell = grid.getCellFromEvent(e);
console.log(cell.row);//Here is the row id, I want to change this row background color
grid.setSelectedRows(cell.row);
e.stopPropagation();
});
})
</script>
</body>
</html>
This is a link to a page if you want to test Sample Page
It looks like you're missing a css file. When I load your sample page and look at the console, this file is missing:
http://payclix.biz/MobiusTrac/slick-default-theme.css
This piece of css would color the row for you:
.slick-row.active .slick-cell {
background-color: #FFB;
}
or with jQuery:
$(".slick-row").click( function(){
$(this).css("background-color", "#FBB");
});
Active row has class "active" and you can add properties to the CSS for this class.

Programmatically declaring the values of a dijit.form.select

I'm trying to declare through a JSON declaration the options for a markup-declared dijit.form.Select widget. Based on what i've read through in the API documentation, it appears that you could pass a new store using setStore() and then it should update, but that has not produced any useful results besides an empty Select widget with a full store. I am wondering if there's some declaration missing from my object, if i'm using the wrong methods, or if there are any other ways to declare these options.
The test markup I've been using is printed below:
<!DOCTYPE HTML>
<html dir="ltr">
<head>
<style type="text/css">
body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="parseOnLoad: true">
</script>
<script>
dojo.require("dijit.form.Select");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.data.ItemFileWriteStore");
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css" />
</head>
<body class=" claro ">
<div class="option" id="option" dojoType="dijit.form.Select"></div>
<script type="text/javascript">
dojo.addOnLoad(function() {
if (document.pub) {
document.pub();
}
var selectOptions = {
name:'selection',
identifier: 'label',
options: [{
label: 'this',
value: '01'
},
{
label: 'that',
value: '02'
},
{
label: 'the other',
value: '03'
},
{
label: 'banana',
value: '04',
},
]};
var aStore = dojo.data.ItemFileReadStore({data: selectOptions});
dijit.byId("option").setStore(aStore, 01);
dijit.byId("option").startup();
});
</script>
</body>
</html>
As #missingno mentioned, using a store for this is probably overkill. You can just use
dijit.form.select.addOption(/*array of options*/).
From your example it would be:
var listOfOptions = [{
label: 'this',
value: '01'
},
{
label: 'that',
value: '02'
},
{
label: 'the other',
value: '03'
},
{
label: 'banana',
value: '04',
},
];
dijit.byId("option").addOption(listOfOptions);
I think you are miss-initializing your store. The options look like the ones used to initialize the plain select instead. Try doing something like:
http://dojotoolkit.org/reference-guide/dojo/data/ItemFileReadStore.html
var store_options = {
identifier: 'label',
label: 'label',
items: [
{label: 'this', value:'01'},
//...
]
}
var store = dojo.data.ItemFileWriteStore({data: store_options})
OTOH, are you sure you need to use a store for this? Unless you want to use a particular store feature (like notification) you can just pass the data directly when you create a select programatically: http://dojotoolkit.org/reference-guide/dijit/form/Select.html

Categories

Resources