Permanently reverse the order of a DataTable in jQuery? - javascript

Let's say I have a Data Table like so:
<table id="history" class="display">
<thead>
<th>Player</th>
<th>Word</th>
<th>Value</th>
<th>Message</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
I have a function that receives a payload from the server and adds a row to the datatable with the relevant information
var history_data_table = $('#history').DataTable({
"pageLength": 5,
"searching": false,
"bLengthChange": false,
"language": {
"emptyTable": "Words that you discover will appear here."
}
});
function liveRecv(word_payload) {
history_data_table.row.add([word_payload.id_in_group,
word_payload.word,
word_payload.word_value,
word_payload.message]
).draw();
Naturally, this will add the row to the end of a paginated table. This table is a list of transactions in a game, and I want to present the most recent transactions to the user, such that every row that's added is added to the top of the data-table. What is the easiest way to achieve this?

You could try this method using jQuery
$('#history tr:first').after("<tr role="row"><td></td><td>add you own row</td></tr>");
or you could use DataTables inner function to access the array of rows
var history_data_table = $('#history').dataTable();
var DisplayMaster = history_data_table.fnSettings()['aiDisplayMaster'];
var tableapi = history_data_table.api();
var getlastrow = DisplayMaster.pop();
DisplayMaster.unshift(getlastrow);
tableapi.draw(false);

Related

how to loop a nested array object in javascript with jquery

Hey im working on a project and i can't seem to get the hang of this. I want to loop through my nested array object "products" so that i can display it all and not just the last index.
// jquery getting our json order data from firebase
$.get("http://localhost:8888/orderslist", (data) => {
// i is for the index of the array of orders
let i = 0;
//for each loop through our array list
$.each(data, function () {
//console.log(data)
//console.log(i);
// is how we arrange the data and show it to the frontpage
$(`<table id = order_table_layout>
<tr>
<th>Customer</th>
<th>Date</th>
<th>Time</th>
<th>Total</th>
<th>Order</th>
<th>Order Status</th>
</tr>
<tr>
<td>${data[i].customer_name}</td>
<td>${data[i].date}</td>
<td>${data[i].time}</td>
<td>${data[i].total} Kr.</td>
<td>
${data[i].products[i].name}
${data[i].products[i].price} Kr.
</td>
<td>
</td>
</tr>
</table>`
).appendTo("#frontpage_new_ordertable");
// counts 1 up for each loop to go through list
i++;
//console.log(i);
});
});
Edit:
An example of the json data I'm working with look like this:
[
{
id: "4WQITi6aXvQJsKilBMns",
customer_name: "Susanne",
date: "22-12-2002",
time: "12:43:19",
total: 222,
products: [
{ name: "product name", price: 100 },
{ name: "product name2", price: 20 }
]
There's a couple of issues in your code. Firstly you're creating a brand new table for every object in the data array. It makes far more sense to instead create a new row in the table for each item.
Also, it appears that you want to loop through the child products array. As such you need an inner loop to create the HTML string for those elements outside of the template literal.
However it's worth noting that it's not good practice to have that much HTML in your JS. A better approach is to have a hidden template tr in your HTML which you can clone, update with the data from the data array, then append to the DOM in the tbody of the table.
With that said, try this:
//$.get("http://localhost:8888/orderslist", (data) => {
// mock response:
let data = [{id:"4WQITi6aXvQJsKilBMns",customer_name:"Susanne",date:"22-12-2002",time:"12:43:19",total:222,products:[{name:"product name",price:100},{name:"product name2",price:20}]},{id:"asjdkjk21ijjjew",customer_name:"Foo Bar",date:"10-05-2020",time:"16:46:16",total:68,products:[{name:"Lorem ipsum",price:50},{name:"Fizz buzz",price:18}]}];
let rows = data.map(item => {
let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
$clone.find('.customer-name').text(item.customer_name);
$clone.find('.date').text(item.date);
$clone.find('.time').text(item.time);
$clone.find('.total').text(item.total + ' Kr.');
let products = item.products.map(prod => `${prod.name}: ${prod.price} Kr.`);
$clone.find('.products').html(products.join('<br />'));
return $clone;
});
$("#frontpage_new_ordertable tbody").append(rows);
//});
tfoot {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="frontpage_new_ordertable">
<tbody>
<tr>
<th>Customer</th>
<th>Date</th>
<th>Time</th>
<th>Total</th>
<th>Order</th>
<th>Order Status</th>
</tr>
</tbody>
<tfoot>
<tr>
<td class="customer-name"></td>
<td class="date"></td>
<td class="time"></td>
<td class="total"></td>
<td class="products"></td>
<td></td>
</tr>
</tfoot>
</table>
<td>${data[i].total} Kr.</td>
<td>
${data[i].products[i].name}
${data[i].products[i].price} Kr.
maybe that's what's wrong?
is the number of the order similar to the number of product in products array?

Display only 3 digits after decimal in DataTables

I am trying to display only 3 digits after decimal point but I'm unable to do so. I tried with toFixed() method but I couldn't succeed.
Here's my fiddle.
HTML source code:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>DATE</th>
<th>CODE</th>
<th>PRODUCT</th>
<th>QUANTITY</th>
<th>UNIT</th>
<th>VALUE</th>
<th>COUNTRY</th>
</tr>
</thead>
<tbody>
<tr>
<td>01/01/2017</td>
<td>84571001</td>
<td>MACHININGCENTRESHORIZONTAL</td>
<td>13</td>
<td>NOS</td>
<td>22.1382568</td>
<td>JAPAN</td>
</tr>
<tr>
<td>03/01/2017</td>
<td>84571001</td>
<td>MACHININGCENTRESHORIZONTAL</td>
<td>33</td>
<td>NOS</td>
<td>54.5104524</td>
<td>JAPAN</td>
</tr>
</tbody>
</table>
Can anyone help me out?
The easiest is to use the built-in number helper :
columnDefs: [{
targets: [5],
render: $.fn.dataTable.render.number(',', '.', 3)
}]
Updated fiddle -> http://jsfiddle.net/ebRXw/3627/ Just an example, follow the link for details about all the options you can use along with the number renderer.
you can define a custom renderer for one or multiple columns.
https://datatables.net/examples/advanced_init/column_render.html)
$('#example').DataTable({
responsive: true,
columnDefs: [{
targets: [5],
render(v){
return Number(v).toFixed(3)
}
}]
});
You could transform the cells' values before you apply DataTable.
Here is how you would do it, assuming the cells that need to be modified have the hi class.
$(document).ready(function() {
$('#example .hi').each(function() {
var num = $(this).html(); // get the content of the cell
num = parseFloat(num); // transform it to a JavaScript number
num = num.toFixed(3); // Limit the number of decimals to 3
$(this).html(num); // Update the HTML content
});
$('#example').DataTable({
responsive: true
});
});

Applying fnFilter to a modified table

Using DataTables 1.9.4 and JQuery 1.4.4.
I'm trying to create a table which filters certain rows based on the visible column. The table is driven by an AngularJS like in-house controller.
When the table is displayed, the filter works fine, but thereafter, if the value changes, the filter is not updated.
The controller consists of an array (one for each row). When the table is updated through it, the filter is not reapplied. How can I make the filter reevaluate each row when the data changes?
HTML as generated by controller:
<table id="table-status">
<thead>
<tr>
<th>visible</th>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>name1</td>
<td>1</td>
</tr>
<tr>
<td>0</td>
<td>name2</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>name3</td>
<td>3</td>
</tr>
</tbody>
</table>
The DataTables initialization:
var oTable = $("#table-status").dataTable( {
"aoColumnDefs": [ { "bVisible": false, "aTargets": [ 0 ] },
{ "bVisible": true, "aTargets": [ 1 ] },
{ "bVisible": true, "aTargets": [ 2 ] } ],
"bSort": false,
"bFilter": true
} );
oTable.fnFilter("1", 0, false, false, false, false);
I'm not entirely sure if this is what you need, but I rolled my own function to display or not some rows, based on a column called Status.
I have a checkbox that can contain the values 0, 1, 2 and 3.
First, I get the regex function associating the values I want to filter:
var filter = "^" + $("#filterStatusCheck option:selected").map(function() {
return this.value;
}).get().join("|") + "$";
Which returns, for instance, ^1|2$, meaning I want to filter the values 1 and 2.
Then, I search() the DataTable, looking for those elements (not me, actually, but rather their search() method.
var t = s.getTable().DataTable();
t.column(8).search(filter, true, false).draw();
Here, on column with the index of 8, I'm doing so that it searches, using the above filter, and then draw() the DataTable again.
In your case, you might want to figure out what event you can attach the above code (maybe right after the row has been updated?). Your filter would be 1 (visible, right?), whereas your column search would be 0 (the first column called visible).
Hope it helps.

How to get information from datatable - javascript - MVC

I have created an ASP.net MVC app and I have created a DataTable [DataTable.net] as follows:
<table id="invoiceTable">
<thead>
<tr>
<th>Invoice ID</th>
<th>Date</th>
<th>Reciept Date</th>
<th>Category</th>
<th>Total Value</th>
<th>Invoice Ref</th>
<th>Client</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#{
foreach (FreeAgentApp.Models.CustomInvoice _invoice in ViewBag.Invoices)
{
<tr>
<td>#_invoice.InvoiceId</td>
<td>#_invoice.Date</td>
<td>#_invoice.RecpDate</td>
<td>#_invoice.Category</td>
<td>#_invoice.TotalValue</td>
<td>#_invoice.InvoiceRef</td>
<td>#_invoice.Client</td>
<td>#_invoice.Status</td>
</tr>
}
}
</tbody>
</table>
And i can get the information from a row when its selected using javascript as follows:
// Row data
$(document).ready(function () {
oTable = $('#invoiceTable').dataTable();
oTable.$('tr').click(function () {
var data = oTable.fnGetData(this);
alert(data);
// ... do something with the array / object of data for the row
});
});
The variable data will provide a string of every value in the row separated by a comma as follows:
"000,26-01-14,27-01-14,001,1000,inv,something ltd,paid"
I want to have all these values separated. Note this could be done by splitting on the comma however a value in the table could contain commas.
How can I separate this string?
According to the DataTables documentation oTable.fnGetData(this); return an array filled with the data of the definitions in the row so you should be able to acces the data directly from data.
var invoiceId = data[0];
var date = data[1];
var recpDate = data[2];
// etc. etc.

How can I refresh a datatable inside a div using JavaScript?

Here is my code:
oTable2 = $('#BigData2').dataTable({
"bLengthChange":false,
"bPaginate":false,
"oLanguage": {
"sZeroRecords": "No records found"
},
"sAjaxSource":'StatusSrv',
// "sDom":'RCT<"clear">lfrtip',
//"aoColumnDefs":[{}]
})
var auto_refresh = setInterval(
function (){
$('#Status_Table').fadeOut('slow').load('SupplyPlanning.jsp
#oTable2.fnDraw()').fadeIn("slow");
}, 6000);
<div id="Status_Table" class="chartFloatLeftInner">
<table id="BigData2" >
<thead >
<tr>
<th><input type="checkbox" onClick="checkall()" name="maincheck" id="maincheck"/></th>
<th title="REQ_NO">REQ_NO</th>
<th title="Retailer Partner number">Retailer num</th>
<th title="STATUS">OVERALL_STATUS</th>
</tr>
</thead>
<tbody></tbody>
</table>
I want to refresh my datatable in a particular time interval so that I am using fndraw but it only redraws the table with the old data. If I insert new data in the database, the new data is not shown after refresh; it shows only the old data.
Probably you would need to add the "bDestroy": true attribute to your datatable code which allow you to rebuild it otherwise once created you can not load it with new data.
Try using append:
$('#Status_Table').append( your table in here);
It work for me

Categories

Resources