I have a DataTable that contains dates that are formatted like this: "/Date(1185336000000)/".
In the following code, I followed DataTable's docs to integrate Moment.js for date conversion---either I'm missing something or my code is written incorrectly. Or both.
Any thoughts on this? I believe part of the issue lies with function loadPH, but I don't want to remove it.
JS snippet:
import $ from 'jquery';
import admissData from '../JSON/sk-admiss.json';
import DataTable from 'datatables.net';
import moment from 'moment';
function loadPH() {
let admissText = admissData.d.results
.filter(x => x.p_h_v !== "")
.map(function(val) {
return {
"PH": val.p_v_h,
"Stuff": val.stuff,
...
...
"Date of Admission": val.dateofadmission,
... // ----- irrelevant info
}
})
$.fn.DataTable.moment('MMM Do YY'); // ---- console error: "default.a.fn.DataTable.moment is not a function"
$('#prohac-table').DataTable({
columns: [
{ data: "PH" },
{ data: "Stuff" },
...
...
{ data: "Date of Admission" },
... // ----- irrelevant info
],
columnDefs: [{
type: 'date',
targets: [4]
}],
data: admissText
});
}
loadPH();
HTML snippet:
<script src="index.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js" integrity="sha384-7aThvCh9TypR7fIc2HV4O/nFMVCBwyIUKL8XCtKE+8xgCgl/PQGuFsvShjr74PBp" crossorigin="anonymous"></script>
<script
src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script
src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script
src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
Update: I did some digging and the solution involved working with columnDefs:
{ data: "x" },
{ data: "y" },
{ data: "z" },
{ data: "zz" },
{ data: "Date of Admission" }, // ----- target
...
{ data: "Classification" }
],
columnDefs: [
{"type":"unix","targets":4,"render": function(data) {
return moment.utc(data, "x").format('MM/DD/YYYY')
}}, // targets must be plural
],
Here is how I would process the strange date format "/Date(1185336000000)/" which I assume to be a Unix time stamp in milliseconds.
First, remove that line from your code: $.fn.DataTable.moment('MMM Do YY');
Then, processStrangeDate() (Feel free to rename it as you like) would be a function to retreive the Unix timestamp and convert it using Moment.js
function parseDate(strangeDate){
return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
}
Here is a simple demo:
var strangeDate = "/Date(1185336000000)/";
// A function to process that strange date format
function processStrangeDate(strangeDate){
return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
}
// Processing example
var strangeDate = "/Date(1185336000000)/";
console.log(processStrangeDate(strangeDate));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
And how to use it in DataTables:
// A function to process that strange date format
function processStrangeDate(strangeDate){
return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
}
// Example in dataTables using columnDef
$("#example").dataTable({
data:[
["Line 1","/Date(1185336000000)/","/Date(1185336000000)/"]
],
columnDefs:[
{
targets:2, render: function(data){ // Target is the column # zero-based
return processStrangeDate(data);
}
}
]
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js" integrity="sha384-7aThvCh9TypR7fIc2HV4O/nFMVCBwyIUKL8XCtKE+8xgCgl/PQGuFsvShjr74PBp" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
<!-- Above is your CDN calls untouched... I just added some CSS below -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/jquery.dataTables.css" rel="stylesheet"/>
<table id="example">
<thead>
<th>Something</th>
<th>Strange Date</th>
<th>Processed Date</th>
</thead>
<tbody>
</tbody>
</table>
CodePen
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Data is in nested object format which i am getting from an api and the data format is
{
"info": {
"makerCommission": "10",
"takerCommission": "10",
"buyerCommission": "0",
"sellerCommission": "0",
"canTrade": true,
"canWithdraw": true,
"canDeposit": true,
"updateTime": "1639767562245",
"accountType": "SPOT",
"balances": [
{
"asset": "BTC",
"free": 0.00000371,
"locked": 0.00000000
},
{
"asset": "LTC",
"free": 0.00000769,
"locked": 0.00000000
}
}
Passing a value info.balances in a function but it is giving an error. i can use object('info.balances') directly and access its data but i want to filter the data so i can get only those value which are greater than 0.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Comment</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- <link rel="stylesheet" type="text/css" href="style.css"> -->
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" />
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="main-body">
<header>
<div id="main">
<table id="table_id" cellspacing="0" width="100%">
<thead>
<tr class="bg-dark">
<th class="grey">asset</th>
<th class="grey">free</th>
<th class="grey">locked</th>
</tr>
</thead>
</table>
</div>
</div>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js"></script>
<script>
function getWalletJSON(data) {
console.log(46, data);
let arr = data.filter(function(elem) {
console.log((elem.free > 0));
return (elem.free > 0)
});
}
</script>
<script>
$(document).ready(function(){
$('#table_id').DataTable( {
ajax: {
// url: 'https://jsonplaceholder.typicode.com/comments',
url: 'http://design.trailingcrypto.com/api/trade/balances?exchange=binance',
dataSrc: getWalletJSON(info.balances)
},
columns: [
// { data: 'asset'},
{ data: null,
orderable: false,
className: 'hvhb',
render: function (data, type, row, ){
let newdata ='';
// if(data.free >= 1 ){
// // console.log(data.asset);\
// newdata = `${data.asset}`
// // return newdata;
// }
// return newdata;
if(data.free >0 ) newdata = newdata + `</br>(${data.asset})`;
console.log(newdata);
return newdata;
}
},
// { data: 'free'},
{ data: null,
orderable: false,
className: 'hvhb',
render: function (data, type, row, ){
// if(data.free >= 1 ){
// console.log(data.free);
let newdata = `${data.free}`;
return newdata;
}
},
// { data: 'locked'},
]
});
})
</script>
</body>
</html>
```
You are not returning anything from your getWalletJSON function. The return statement that you do have belongs to the filter function.
function getWalletJSON(data) {
console.log(46, data);
let arr = data.filter(function(elem) {
console.log((elem.free > 0));
return (elem.free > 0)
});
return arr;
}
I wanna make my tags have space, live ketchup v2 but for now it's generating two tags ketchup and v2.
I took the simple example of making tags or search for existed
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />
</head>
<body>
<select class="form-control select2" multiple="multiple" style="width: 100%;"></select>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
<script>
$('.select2').select2({
data: ["Piano", "Flute", "Guitar", "Drums", "Photography"],
tags: true,
maximumSelectionLength: 10,
tokenSeparators: [',', ' '],
placeholder: "Select or type keywords",
//minimumInputLength: 1,
//ajax: {
// url: "you url to data",
// dataType: 'json',
// quietMillis: 250,
// data: function (term, page) {
// return {
// q: term, // search term
// };
// },
// results: function (data, page) {
// return { results: data.items };
// },
// cache: true
// }
});
</script>
</body>
</html>
So, I want to do only with enter create a tag, not with space or something like that.
Change your code like this and check.
tokenSeparators: [',']
This will allow only enter key or comma to create a tag.
Good morning I'm having this little issue using Datatables inside a bootstrap modal that should be showing a SQLServer query (just a select), its required to be able to print as an Excel file or other formats but I'm receiving the error in console "DataTables Cannot read property 'aDataSort' of undefined" And in front of that error it shows "jquery-3.5.1.js:4055" so I assume this should be the issue.
Since I need to export results as a format, I found this https://datatables.net/extensions/buttons/examples/initialisation/export.html
And I was reading through different websites and also here and looks like the problem is how dependencies are defined but I've tried different ways and its not working so I'm not sure what could be the problem...
These are my dependencies:
<meta charset="utf-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<link rel="stylesheet" href="../../bootstrap-4.5.0-dist/css/bootstrap.css" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script src="js/functions.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="js/datatables.js"></script>
<script src="js/Buttons-1.6.2/js/buttons.bootstrap4.js"></script>
<script src="js/DataTables-1.10.21/js/jquery.dataTables.js"></script>
<script src="js/JSZip-2.5.0/jszip.js"></script>
<script src="js/pdfmake-0.1.36/pdfmake.js"></script>
<script src="js/pdfmake-0.1.36/vfs_fonts.js"></script>
This is the table inside the modal
<table id="table_to_show"></table>
This is the function in the same file that should be showing the table.
<script type="text/javascript">
$(document).ready(function() {
$('#table_to_show').DataTable( {
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
} );
} );
</script>
And this is the table itself that's generated for the SELECT:
$table="";
if ($result) {
$data = sqlsrv_has_rows($result);
if ($data === true) {
while ($data = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$table=$table.'<tr>
<td>'.$data['ID'].'</td>
<td>'.$data['NAME'].'</td>
<td>'.$data['LNAME'].'</td>
<td>'.$data['number1'].'</td>
<td>'.$data['number2'].'</td>
<td>'.$data['MOBILE'].'</td>
<td>'.$data['MRETIR'].'</td>
</tr>';
}
}
}
sqlsrv_close($conn);
echo '<table class="table table-stripped">
<thead>
<th>Id</th>
<th>Name</th>
<th>Last Name</th>
<th>Number 1</th>
<th>Number 2</th>
<th>Mobile #</th>
<th>Retired?</th>
</thead>
<tbody>'.$table.'
</tbody>';
That's kinda all I have... anyone can help me with this issue?, I've been trying to solve it for 2 days, maybe 3...
Thanks in advance
Try using json_encode for your PHP output Here is some of my MYSQLI Sample
$sqlSelect = "SELECT * FROM table";
$result = mysqli_query($conn, $sqlSelect);
$someArray = [];
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($someArray, [
'ID' => $row['ID'],
'NAME' => $row['NAME'],
'LNAME' => $row['LNAME'],
'ETC' => $row['ETC']
]);
}
}
$json = json_encode($someArray);
echo ($json);
Then The JQuery
$.ajax({
url: 'php_file.php',
type: "GET",
success: function(res){
var obj = JSON.parse(res);
console.log(obj);
$('#table_to_show').DataTable({
dom: 'Bfrtip',
destroy: true,
processing: true,
"data" : obj,
"columnDefs": [{
"defaultContent": "-",
"targets": "_all"
}],
buttons : [ 'copy', 'csv', 'excel', 'pdf', 'print' ],
"columns": [
{ "data": "ID" },
{ "data": "NAME" },
{ "data": "LNAME" },
{ "data": "ETC" }
]
})
;
},
error: function(xhr){
alert("Error Occured!", "error")
}
});
HTML
<table id="table_to_show" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>LNAME</th>
<th>ETC</th>
</tr>
</thead>
</table>
DataTable Button CDN
https://code.jquery.com/jquery-3.5.1.js
https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js
https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js
https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js
https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js
https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js
https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js
I use jQuery DataTables in my code.
One of my columns has values, like:
AB 05-05-2019
CD 01-05-2019
EF 09-05-2019
When I click this column's header, I want it to get sorted only by using date, not by the prefix ('AB', 'CD', 'EF'). The result should be like:
CD 01-05-2019
AB 05-05-2019
EF 09-05-2019
What I've tried is, inserting a hidden column only with the date and when I sort column with the prefix, I sort my hidden column using JavaScript.
But, is there any proper way by using default configuration of jQuery DataTables?
Assuming, your values are dates in the format 'DD-MM-YYYY' prefixed by two characters and a space, you may built your own little sorting plug-in, with custom sorting function like that:
(first, second) => {
const firstDate = new Date(first.substr(3).split('-').reverse().join('-'));
const secondDate = new Date(second.substr(3).split('-').reverse().join('-'));
return firstDate - secondDate;
};
So, your complete example might look something like this:
//source data
const srcData = [{
id: 1,
value: 'AB 05-05-2019'
}, {
id: 2,
value: 'CD 01-05-2019'
}, {
id: 3,
value: 'EF 09-05-2019'
}
];
//datatable initialization
const dataTable = $('#mytable').DataTable({
dom: 't',
data: srcData,
columns: ['id', 'value'].map(header => ({
title: header,
data: header
})),
columnDefs: [{
type: 'prefixedDate',
targets: 1
}
]
});
//extract Date part of the string
const extractDate = str => new Date(str.substr(3).split('-').reverse().join('-'));
//custom sorting
Object.assign($.fn.DataTable.ext.oSort, {
'prefixedDate-asc': (a, b) => extractDate(a) - extractDate(b),
'prefixedDate-desc': (a, b) => extractDate(b) - extractDate(a),
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" 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>
<table id="mytable"></table>
</body>
</html>
When trying to update a chart in React using the sample given by FusionCharts, I can't get the chart to update. It is definitely changing the value, which I found out by adding this line:
console.log(revenueChartConfigs.dataSource.data[2].value);
The value is changing from 590000 to 420000 as desired, but the chart does not update. Does anyone have advice on this? I have pasted my code below. Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/fusioncharts.js"></script>
<script type="text/javascript" src="js/fusioncharts.charts.js"></script>
<script type="text/javascript" src="js/fusioncharts.gantt.js"></script>
<script type="text/javascript" src="js/fusioncharts.maps.js"></script>
<script type="text/javascript" src="js/fusioncharts.powercharts.js"></script>
<script type="text/javascript" src="js/fusioncharts.ssgrid.js"></script>
<script type="text/javascript" src="js/fusioncharts.treemap.js"></script>
<script type="text/javascript" src="js/fusioncharts.widgets.js"></script>
<script type="text/javascript" src="js/fusioncharts.zoomscatter.js"></script>
<script src="https://unpkg.com/react#15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/react-fusioncharts.min.js"></script>
<script type='text/babel'>
$(document).ready(function(){
var myDataSource = {
chart: {
caption: "Top 5 stores in last month by revenue",
subCaption: "Harry's SuperMart",
numberPrefix: "$",
theme: "fint"
},
data: [{
label: "Bakersfield Central",
value: "880000"
}, {
label: "Garden Groove harbour",
value: "730000"
}, {
label: "Los Angeles Topanga",
value: "590000"
}, {
label: "Compton-Rancho Dom",
value: "520000"
}, {
label: "Daly City Serramonte",
value: "330000"
}]
};
var RevenueChart = React.createClass({
/**
** `getInitialState()` method is used to initialize the state of the
** the `RevenueChart` component.
**/
getInitialState: function () {
return {
eventTarget: ''
};
},
/**
** The `handleClick()` function is defined in the `RevenueChart` component.
** This function is configured to store the state of the `eventTarget` using
** the `setState()` method of React. This is binded to button click.
**/
handleCLick: function () {
this.setState({
eventTarget: 'btn-update-data'
});
},
render: function () {
var revenueChartConfigs = {
id: "revenue-chart",
renderAt: "revenue-chart-container",
type: "column2d",
width:600,
height: 400,
dataFormat: "json",
dataSource: myDataSource,
eventTarget: this.state.eventTarget,
impactedBy: ['btn-update-data']
};
/**
** Using the state, we update the `label` and `value` for the third and
** fourth data plots in the `render()` method of RevenueChart. The configuration
** object that is passed as props is used to refer to the `label`
** and `value` attributes of the `data` object array.
**/
if (this.state.eventTarget && this.state.eventTarget.length != 0) {
revenueChartConfigs.dataSource.data[2].label = "Art Supply Store";
revenueChartConfigs.dataSource.data[2].value = "420000";
revenueChartConfigs.dataSource.data[3].label = "P.C. Richard & Son";
revenueChartConfigs.dataSource.data[3].value = "320000";
}
else {
revenueChartConfigs.dataSource = myDataSource;
}
console.log(revenueChartConfigs.dataSource.data[2].value);
return (
<div>
/** The `FusionCharts` React component is used to render the chart. **/
<react_fc.FusionCharts {...revenueChartConfigs} />
/** Create a button, which when clicked will call the `handleClick()` function. **/
<a id='btn-update-data'
onClick={this.handleCLick}
className="btn btn-default"
href="#">{'Click me to change data'}</a>
</div>
);
}
});
ReactDOM.render(
<RevenueChart />,
document.getElementById('chart-container')
);
});
</script>
</head>
<body>
Hello
<div id="chart-container"></div>
</body>
</html>