DataTable plugin using aurelia updating data - javascript

I'm using the DataTables and DatePicker plugins with Aurelia.
I basically want the user to select a date and have the data table render the data for that date but with my current code there seems to be an issue with the datatable once the data changes. As soon as the data changes the formatting on the datatable plugin seems off and the sorting, scrolling buttons don't work.
I tried adding the datepicker on a jsfiddle but I had no luck as you have to add some configuration to package.json and I can't seem to figure that out. If anyone could give any hints I would really appreciate it. Let me know if you have any questions
pickerChanged() {
this.picker.events.onChange = (e) => {
this.data = [];
let inputDate = new Date(e.date.format('YYYY-MM-DD') + ' 00:00');
let data = (demoData as any).default;
for (let row of data) {
let rowDate = new Date((row as any).date);
if (inputDate.getTime() >= rowDate.getTime()) {
this.data.push(row);
}
}
console.log(4444, this.data);
$(document).ready(function() {
$('#dataTable').DataTable( {
"scrollY": "280px",
"scrollCollapse": true,
"paging":false,
"searching": false,
"info": false,
"language": {
"emptyTable": " "
}
} );
} );
};
}
<abp-datetime-picker element.bind="picker"></abp-datetime-picker>
<div class="row pt-2">
<div class="col-12">
<table class="table" id="dataTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Receipt #</th>
<th>Invoice number</th>
<th>Date</th>
<th>Total</th>
<th>Balance</th>
<th>Payment</th>
</tr>
</thead>
<tbody>
<tr repeat.for="row of data">
<td>${row.id}</td>
<td>${row.name}</td>
<td>${row.receiptNumber}</td>
<td>${row.invoiceNumber}</td>
<td>${row.date}</td>
<td>${row.total}</td>
<td>${row.balance}</td>
<td>${row.payment}</td>
</tr>
</tbody>
</table>
<div class="text-center" if.bind="!data.length">No records available. Please select a valid date</div>
</div>
</div>

After a few hours of investigating the issue I finally figured it out. The problem with my old code was that I was passing data to the datatable using ${row.id} for example instead of using the data parameter with datatable like follows.
$('#dataTable').DataTable({
data: this.data,
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'receiptNumber' },
{ data: 'invoiceNumber' },
{ data: 'date' },
{ data: 'total' },
{ data: 'balance' },
{ data: 'payment' },
]
});
<div class="row pt-2">
<div class="col-12">
<table class="table" id="dataTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Receipt #</th>
<th>Invoice number</th>
<th>Date</th>
<th>Total</th>
<th>Balance</th>
<th>Payment</th>
</tr>
</thead>
</table>
</div>
</div>
and then calling this function whenever you want to update your data
$('#dataTable').DataTable().clear().rows.add(this.data).draw();

Related

Datatables not showing my data but after applying filter

I am populating a table via Ajax JSON with datatables, this is my JS code:
$(document).ready(function () {
$.ajax({
url: "../WebService.asmx/LoadUsers",
type: 'POST',
datatype: 'json',
//content: 'json', lo mismo que arriba
contentType: 'application/json; charset=utf-8',
success: function (data) {
var datos = JSON.parse(data.d);
// METODO JQUERY DATATABLES Documentación
$('#tblUsers').DataTable({
data: datos,
columns: [
{ 'data': 'id' },
{ 'data': 'username' },
{ 'data': 'password' },
{ 'data': 'dregistered' },
{
'data': null,
'defaultContent': "<img src='../assets/img/delete.png' id='btnDel' style='width: 22px; cursor:pointer;' />"
}
//
],
responsive: true
});
/*DataTables instantiation.*/
/*$("#tblUsers").DataTable();*/
},
error: function () {
alert('Fail!');
}
});
});
Html table:
<table id="tblUsers" class="table table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Fecha</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Fecha</th>
</tr>
</tfoot>
</table>
My table after loading html page
Is not showing data, it seems like not rendering at first, but after applying column filter or changing entries, the data is showing:
Filtering by entries number
Filtering by column order
Am I missing something? 🤔
Your problem is probably that you are trying to set 5 columns of data (even if the 5th one has data: null) but you have only 4 columns in your HTML <table>.
If you look at your console, probably there should be some error like Cannot read property 'style' of undefined or similar.
So, the loading of the data inside the table is interrupted by the error.
Change your HTML to this (adding an extra <th></th>) and it should go fine:
<table id="tblUsers" class="table table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Fecha</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Fecha</th>
<th></th>
</tr>
</tfoot>
</table>

jQuery Datatable row grouping total items display "Show 1 to n entries"

I am trying to achieve the row group,
I found this js http://cdn.rawgit.com/ashl1/datatables-rowsgroup/v1.0.0/dataTables.rowsGroup.js plugin to achieve like below,
But when I am using this plugin, number of entries is showing wrong.
Here is my sample code
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th>First Group</th>
<th>Second Group</th>
<th>Third</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS Code:
var data = [{"first":"subgroup1","second":"group1","third":"third data"},
{"first":"subgroup1","second":"group1","third":"third data"},
{"first":"subgroup2","second":"group2",
"third":"lorem ipsum data"},
{"first":"subgroup2","second":"group2",
"third":"lorem ipsum data"},
]
$('#example').DataTable({
columns:[
{
name:"first",
data:"first"
},
{
name:"second",
data:"second"
},
{
name:"thirddata",
data:"third"
},
],
data:data,
rowsGroup: [
'first:name',
'thirddata:name'
]
});
Updated in JS Fiddle : https://jsfiddle.net/r2f87hg6/2/
Please suggest with this datatable to display number of entries by grouped.
Thanks

Datatables.js: How to read in JSON

So I've been messing around with Datatables.js but I can't seem to populate it with results. So I have a Java servlet that returns the following JSON:
[{"fileName":"report (1).xlsx","fileSize":"82 KB","fileDate":"07/13/2016 15:19:43"},{"fileName":"report (2).xlsx","fileSize":"11 KB","fileDate":"07/07/2016 11:35:47"},{"fileName":"report (3).xlsx","fileSize":"11 KB","fileDate":"07/07/2016 11:35:47"},{"fileName":"report (4).xlsx","fileSize":"9 KB","fileDate":"07/13/2016 15:20:54"}]
My HTML looks likes:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Size</th>
<th>Date</th>
</tr>
</thead>
</table>
My JS looks like:
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"processing": true,
"ajax": {
"url": "/TR3Application/FileViewerServlet",
"dataSrc": "",
"type": "GET"
}
} );
});
When I just call AJAX and log what it returns, I'm getting the exact same JSON response from the servlet. But the Datatables don't seem to populate anything. What am I doing wrong?
You need to let dataTables knows the columns - Json mapping.
<tr>
<th data-data="fileName">Name</th>
<th data-data="fileSize">Size</th>
<th data-data="fileDate">Date</th>
</tr>

bootstrap-table-filter-control extension doesn't work in bootstrap-table

I use bootstrap-table and would like to use table-filter-control extension. In this example you can see how to use this extension. When I want to use this extension for more columns, it doesn't work. In my example filter works only for one column.
jsfiddle
html
<table ref="mainTable" class="table table-striped table-bordered table-hover"
cellSpacing="0" id="mainTable" data-show-toggle="true"
data-show-columns="true" data-search="true" data-pagination="true" data-filter-control="true">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Customer Name" data-sortable="true" data-filter-control="select">Customer Name</th>
<th data-field="Location Type" data-sortable="true">Location Type</th>
<th data-field="Location" data-sortable="true" data-filter-control="select">Location</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Cap Corp</td>
<td>Main</td>
<td>Norwalk CT 06851</td>
</tr>
<tr>
<td></td>
<td>Cap Corp</td>
<td>Other</td>
<td>Norwalk CT 06851</td>
</tr>
<tr>
<td></td>
<td>Tel</td>
<td>Main</td>
<td>Slough SL1 4DX</td>
</tr>
<tr>
<td></td>
<td>Tel</td>
<td>Other</td>
<td>London W1B 5HQ</td>
</tr>
</tbody>
</table>
data-filed should have not spaces, try to change
data-field="Customer Name"
to
data-field="CustomerName"
I updated your jsfiddle and filter-control works.
http://jsfiddle.net/5h595r6g/9/
However it would be great to implement filter options updating to available values, as I described in this post:
bootstrap table filter-control - how to unset unnecessary values from select options
I actually put select2 boxes in the headers, and then used the params feature to pass the code to the server. I made for a much nicer solution. My code isn't with me but if you are interested in it I can pass a sample along Monday.
Edited to add example.
Basic Table
<table id='90day' class='table table-striped' data-filter-control='true'>
<thead>
<tr>
<th></th>
<th><select id='findfield' class='form-control gosearch'><option></option></select></th>
<th><select id='findwellname' class='form-control gosearch'><option></option></select></th>
</tr>
</thead>
</table>
Initialize the select2
$('#90day').on('post-header.bs.table', function () {
$('#findfield').select2({
width: '100%',
placeholder: 'Field',
allowClear: true,
SingleSelection: true,
ajax: {
url: 'selectfield90day.php?active=y',
dataType: 'json',
//delay: 250,
data: function (params) {
$('#findfield').empty();
var d = new Date();
var n = d.getTime();
return {
q: params.term,
n: n
};
},
processResults: function (data) {
return { results: data };
}
}
});
$('#findwellname').select2({
width: '100%',
placeholder: 'Name',
allowClear: true,
ajax: {
url: 'selectwellname90day.php?active=y',
dataType: 'json',
delay: 250,
data: function (params) {
$('#findwellname').empty();
var d = new Date();
var n = d.getTime();
return {
q: params.term,
field: $('#findfield').text(),
pad: $('#findpad').text(),
n: n
};
},
processResults: function (data) {
return {
results: data
};
}
}
});
//refresh on any select2 change
$('.gosearch').on('select2:close', function(){
$('#90day').bootstrapTable('refresh');
});
});
Finally table initialization
$('#90day').bootstrapTable({
url: ...,
columns:[
...
],
queryParams: function(params){
params['field']=$('#findfield').text();
params['well_name']=$('#findwellname').text();
return params;
}
});

How to hide/display rows in datatables?

I am trying to hide/display certain rows based on data from a hidden column. my table structure looks like:
<table id="agent_search" cellpadding="0" cellspacing="0" border="0" class="table table-striped">
<thead>
<th>Agent ID</th>
<th>Agent Name</th>
<th>ID Number</th>
<th>Mobile Number</th>
<th>Team Name</th>
<th>Status</th>
<th></th>
</thead>
</table>
I am trying to hide/show records based on the Status column, using a checkbox. If the status == DEREGISTERED I want to exclude it from the table (unchecked checkbox).
I adapted my code from what was done here:
$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
// does not run this
console.log("GOTHRERE");
if ('agent_search' == oSettings.nTable.id) {
// console.dir(oSettings);
console.dir(aData);
var dereg = aData[5];
console.log(dereg);
if (dereg == "DEACTIVATED"){
return $('#toggle_deregistred').is(':checked');
} else {
return $('#toggle_deregistred').is(':not:checked');
}
}
return true;
});
I have tried using $.fn.dataTableExt.afnFiltering witch is used for custom filtering, only to find that I can not do it. It was once possible in previous versions of dataTables as in this case , but as it turns out it was a bug that allowed it to be possible :|.
Is there a way that I can filter out rows based on if their Status with the use of a checkbox? or is there something in the api I can use that I have over looked?
UPDATE:
I have made a jsfiddle in which it is working, how ever in the process of adapting my code to put it in jsfiddle, I noticed that it is bServerSide that is causing the $.fn.dataTableExt.afnFiltering not to work. Is there a work around or another way to user Server-side processing?
I found an alternate way to the checkbox of hiding/displaying.
I use Bootstrap 3 tabs to apply different filters:
<ul class="nav nav-tabs form-tabs" id="search-tabs">
<li id="basic-list" class="active"><a data-toggle="tab" data-dtname="all" href="#all">All</a></li>
<li class="" id="dereg-list"> <a data-toggle="tab" data-dtname="dereg" href="#dereg">Deregistered</a></li>
</ul>
<br>
<div class="tab-content">
<fieldset id="all" class="tab-pane active">
<table id="agent_search" cellpadding="0" cellspacing="0" border="0" class="table table-striped">
<thead>
<th>Agent ID</th>
<th>Agent Name</th>
<th>ID Number</th>
<th>Mobile Number</th>
<th>Team Name</th>
<th>Status</th>
<th></th>
</thead>
</table>
</fieldset>
<fieldset id="dereg" class="tab-pane ">
<table id="dereg_agent_search" cellpadding="0" cellspacing="0" border="0" class="table table-striped">
<thead>
<th>Agent ID</th>
<th>Agent Name</th>
<th>ID Number</th>
<th>Mobile Number</th>
<th>Team Name</th>
<th>Status</th>
<th></th>
</thead>
</table>
</fieldset>
</div>
I first initialize the table on the first tab all which uses bServerSide=true and for the other table(when I switch to the other tab) I do:
$('#search-tabs a').click(function(e) {
e.preventDefault();
$(this).tab('show');
if (this.dataset["dtname"] == "all") {
oTable.fnDraw();
} else if (this.dataset["dtname"] == "dereg") {
var data = $("form").serialize();
$.post(
url, data
).success(function(data){
console.log(data.aaData);
kTable = $('#dereg_agent_search').dataTable( {
"sScrollY": "250px",
"data": data.aaData,
"destroy" : true,
"sDom": "<'row'<'col-sm-6'><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'>>S",
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": [ 6 ],
"sWidth":"150px",
"mRender": function( data, type, full ){
return "<div class='btn-group'><a href="+full[6][0]+" class='btn btn-default btn-sm'>View</a><a href="+full[6][1]+" class='btn btn-default btn-sm'>Edit</a></div>"
}
},
{
"bSortable": true,
"aTargets": [ 0 ],
"sWidth":"150px",
"mRender": function( data, type, full ){
if (full[5] == "DEACTIVATED"){
return "<a href="+full[6][0]+" class='DEACTIVATED'>"+data+"</a>"
} else{
return ""+data+""
}
}
},
{"aTargets": [ 4 ], "sWidth":"250px" },
{"aTargets": [ 5 ], "bVisible":false},
],
"bDeferRender": true,
"bStateSave": true
} );
});
kTable.fnDraw();
}
});
Notice that I get the data to populate the table from the server - using a jQuery $.post request, and then I use datatables' data attribute to populate the table.
I hope This can Help someone.

Categories

Resources