datatables.net select first row in initComplete selects wrong row with default sort - datatables

I want to select first row in the table. I do so in the initComplete-event:
"initComplete": function() {
var t = $(gridId).DataTable();
t.row(0).select();
}
This works fine, but if I get the data unsorted and I implement a default ordering, the wrong row is selected because it's not the first row one anymore.
"order": [[ 2, "desc" ]]

Use the selector-modifier { order: 'current' } :
...
initComplete: function() {
this.api().row( {order: 'current' }, 0).select();
}
This will select the first row regardless of ordering and sorting.
demo -> http://jsfiddle.net/cr49g371/

Related

How to generate jQuery DataTables rowId client side?

The jQuery DataTables reference shows an example of setting the rowId option to a column from the data source (server side). This setting is used for the "select" extension and retaining row selection on Ajax reload.
Is there any way to generate the row identifier value 1) client side, or 2) as a combination of multiple columns from the data source?
Example data source:
{
"data": [
{
"aid": 5421,
"bid": 4502,
"name": "John Smith"
}
}
Code:
$("#datatable").DataTable({
select: true,
//rowId: "aid" each row ID is the value of the "aid" column
// e.g., <tr id="5421">
//rowId: 0 each row ID is the value of the 0-indexed column
// e.g., <tr id="5421"> (same as above)
rowId: [0, 1] // How? row ID combined value of 2+ columns
// e.g. <tr id="5421-4502">
rowId: "random" // How? random generated client-side ID
// e.g., <tr id="id34e04">
});
Apparently there's no way to do this directly. As a workaround, you could use the ajax.dataSrc option and/or the rowId option:
// Example using dataSrc option to manipulate data:
$("#example").dataTable({
ajax: {
url: "data.json",
dataSrc: function (json) {
for (var i = 0, ien = json.data.length; i < ien; i++) {
json.data[i][0] = 'View Message';
}
}
}
});
This worked for me:
$("#datatable").DataTable({
...
'createdRow': function(nRow, aData, iDataIndex) {
$(nRow).attr('id', 'row' + iDataIndex); // or if you prefer 'row' + aData.aid + aData.bid
},
...
});
I updated it from a question that seems to be a duplicate of this one. The createdRow callback is documented here.

Sorting date in datatable

I'm trying to sort dates in my datatable like DD/MM/YYYY (day, month, year) .
I was following https://datatables.net/plug-ins/sorting/ .
but all the date sorts seem to be deprecated and point to the datetime plugin: https://datatables.net/blog/2014-12-18
I don't seem to be able to get the datetime plugin working to sort. I tried the old way, with date. The initialize looks like this:
var historiektable = $('#dataTableHistoriek').DataTable({
"paging" : false,
"ordering" : true,
"scrollCollapse" : true,
"searching" : false,
"columnDefs" : [{"targets":3, "type":"date"}],
"bInfo": true
});
Without sorting it shows the table results like this:
When I put ordering:true 2 of the 2016 dates appear somewhere else in the list (so, not in order you would expect)
With everything pointing at Moment I thought I needed to sort with that. But I'm not sure how.
I saw $.fn.dataTable.moment('DD.MM.YYYY'); somewhere, but I understood that the fn doesn't work with this newest version of datatables anymore?
Anyone knows how to sort dates?
Use date-eu sorting plugin to sort dates in the format DD/MM/YY.
Include the following JS file //cdn.datatables.net/plug-ins/1.10.11/sorting/date-eu.js and use the code below:
var historiektable = $('#dataTableHistoriek').DataTable({
"paging" : false,
"ordering" : true,
"scrollCollapse" : true,
"searching" : false,
"columnDefs" : [{"targets":3, "type":"date-eu"}],
"bInfo": true
});
The example of Gyrocode.com seems the most effective. A recent solution says to use Moments.js but it does not work in my case. date-eu is deprecated by DataTables but it works perfectly.
If you want to sort by date and time using the date format dd/MM/yyyy HH:mm, use date-euro in the same way.
var table = $('#example-table').DataTable({
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
For beginners, add the JS file date-euro to your site. Then add "columnDefs" in your code to indicate which column date-euro should be applied: targets = indicates the column containing the dates to sort, type = indicates the date-euro function to apply to the column. Finally, add "order" to apply the sort you want.
Please look into this answer for an alternate way to sort data by date.
Sample code::
<td data-search="21st November 2016 21/11/2016" data-order="1479686400">
21st November 2016
</td>
$('#dataTable').DataTable({
"order": [[10, 'desc']],
});
Thank You,
Happy Coding :)
Please refer to this pen: https://codepen.io/arnulfolg/pen/MebVgx
It uses //cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js and //cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js for sorting datatable
To sort the table by default use:
$.fn.dataTable.moment('DD/MM/YY');
$('#example').DataTable({
"order": [[ 3, "desc" ]]
});
Following Plasebo's example works, but in my case the MySQL DATE_FORMAT was sorting on month value, not entire date. My solution was to remove the DATE_FORMAT from my SQL statement.
$(document).ready(function() {
$.fn.dataTable.moment('DD/MM/YY');
$('.happyTable').DataTable({
"ordering": true,
"order": [[ 1, "desc" ]],
});
});
DATE_FORMAT(date,'%m/%d/%Y')
"2003-12-30 00:00:00"
results in "12/30/2003" but sorts on month value.
You can do your own comparator in order to keep the control of how is ordering the dates.
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"ddMmYyyy-pre": function (a) {
a = a.split('/');
if (a.length < 2) return 0;
return Date.parse(a[0] + '/' + a[1] + '/' + a[2]);
},
"ddMmYyyy-asc": function (a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"ddMmYyyy-desc": function (a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
As you can see in the above comparator you can choose how to parse the date depending on your data.
And in the columns definition:
"columnDefs": [
{
targets: [4], type: "ddMmYyyy"
}]
For me, using ASP.NET core 3.1 with MVC, I used a data-sort attribute on my <td> for the datatables:
<td data-sort="#(item.DueDateTime.Ticks)">
#Html.DisplayFor(modelItem => item.DueDateTime)
</td>
No plug-ins needed
See this link:
https://datatables.net/examples/advanced_init/html5-data-attributes.html
There's an ugly hack that I've used in the past especially when I couldn't quickly modify the DataTable javascript. You can add a hidden span that has the date in a sortable format.
<td><span style="visibility:hidden">2006-12-21</span>21/12/2006</td>
test
strong text
$.fn.dataTableExt.oSort['time-date-sort-pre'] = function(value) {
return Date.parse(value);
};
$.fn.dataTableExt.oSort['time-date-sort-asc'] = function(a,b) {
return a-b;
};
$.fn.dataTableExt.oSort['time-date-sort-desc'] = function(a,b) {
return b-a;
};
var table = $('#example').DataTable({
columnDefs : [
{ type: 'time-date-sort',
targets: [0],
}
],
order: [[ 0, "desc" ]]
});

Filter other columns based on first columns

I'm using jquery data tables and I'm assigning an array of values to the initialization of the data table. The table basically looks like this.
based on an an radio button I would like to limit the items that are display in the table and the items that are searched in the table.
For my example it would be based on the "Chart column". I want to limit the table to only show the items that are based on chart "D" or Chart "S". Here is how I'm initializing the table.
if (!$.fn.DataTable.isDataTable( '#fundLookUptbl' ) ) {
fundTable = $('#fundLookUptbl').DataTable( {
data: funds,
columns: [
{ "mData": "chart" },
{ "mData": "fund" },
{ "mData": "orgDefault" },
{ "mData": "progDefault" }
]
} );
var filteredData = fundTable
.columns( [0, 1] )
.data()
.eq( 0 )
.filter( function ( value, index ) {
return value = 'D' ? true : false;
} );
}
This is obviously not working, and the filterData variable is a lousy attempt on trying to make it work. I'm having a hard time understanding the API's. So the question is , How can initialize the table to only show the items that are based on a given chart. I know that I can remove the items of the array but i don't want to do that since I would simple like to be able to switch between chart "D" and "S" but still continue to search through the other columns.
I believe that filtering the column would solve your problem.
table.column(0).search('Bruno').draw()
So you could just filter the column when the radio button selection change
Here is a fiddle example
I´m not sure to be understanding what you want to do but here are some options:
One way is selecting by default value example "s". You can use a dropdown is easier to handled .Then select with jQuery the dafault value "s" on that dropdown and add a function
$("#DropdownId").change(function () {
var chart=$("#DropdownId").val();
});
$.ajax({
url: "url")",//url to reload page with new value
type: "POST",
data: {chart:chart},
success: function (data) {
}
});
});
on this way the filter is on backend. If you want to do something on the row depending of a column value you shoud to add something like this
"fnRowCallback": function (nRow, mData, iDisplayIndex, iDisplayIndexFull) {
if (mData["chart"] =="s") {
return nRow;
}
},
Datatables: custom function inside of fnRowCallback.
Good luck
fundTable.order( [0, 'asc'] );
Try that or look at this particular page for reference:
https://datatables.net/reference/api/order%28%29
Basically orders in pair of columnIndex in either asc(ending) or desc(ending) order.

jQuery Datatables highlighting row

I'm using datatables version 1.9.4 and am having a problem with adding a class to certain rows.
I have multiple datatables, all with class 'display'. I'm using jQuery tabs to display each datatable on a separate tab.
All is working well, except I want to add a class to a table row depending on the column values; if column 6 is less than column 14, I want to add myClass.
I've found suggestions to use fnRowCallback, but I'm getting random results, such as sometimes if column 6 is less than column 14, myClass gets added correctly, but other times if column 14 is less than column 6 myClass still gets added!
This doesn't happen for all rows though, so it's pretty random.
Here's the code I'm using
$(document).ready(function() {
$('.display').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bProcessing": true,
"bServerSide": true,
"bScrollCollapse": true,
"sScrollY": "300px",
"sAjaxSource": "ajax.php",
"sDom": '<"H"lfr>t<"F"ipS>',
"oScroller": {
"loadingIndicator": true
},
"fnRowCallback": function( nRow, aData ) {
var $nRow = $(nRow);
if (aData[6] < aData[14]) {
$nRow.addClass("myClass");
}
return nRow
}
});
});
Is there something wrong with what I've done, or is it because I'm using multiple tables?
I think I have this working, but there is probably a cleaner way, so if anyone knows of a better way of doing this, please let me know!
I'm looping through all the rows for each table once the table has been drawn.....
"fnDrawCallback": function( oSettings ) {
for (var i = 0, row; row = oSettings.nTable.rows[i]; i++) {
price = Number(row.cells[4].innerHTML.replace(/[^0-9\.]+/g,""));
average = Number(row.cells[6].innerHTML.replace(/[^0-9\.]+/g,""));
if (price < average) {
row.className = row.className + " myClass";
}
}
}

Rally Lookback: help fetching all history based on future state

Probably a lookback newbie question, but how do I return all of the history for stories based on an attribute that gets set later in their history?
Specifically, I want to load all of the history for all stories/defects in my project that have an accepted date in the last two weeks.
The following query (below) doesn't work because it (of course) only returns those history records where accepted date matches the query. What I actually want is all of the history records for any defect/story that is eventually accepted after that date...
filters :
[
{
property: "_TypeHierarchy",
value: { $nin: [ -51009, -51012, -51031, -51078 ] }
},
{
property: "_ProjectHierarchy",
value: this.getContext().getProject().ObjectID
},
{
property: "AcceptedDate",
value: { $gt: Ext.Date.format(twoWeeksBack, 'Y-m-d') }
}
]
Thanks to Nick's help, I divided this into two queries. The first grabs the final history record for stories/defects with an accepted date. I accumulate the object ids from that list, then kick off the second query, which finds the entire history for each object returned from the first query.
Note that I'm caching some variables in the "window" scope - that's my lame workaround to the fact that I can't ever quite figure out the context of "this" when I need it...
window.projectId = this.getContext().getProject().ObjectID;
I also end up flushing window.objectIds (where I store the results from the first query) when I exec the query, so I don't accumulate results across reloads. I'm sure there's a better way to do this, but I struggle with scope in javascript.
filter for first query
filters : [ {
property : "_TypeHierarchy",
value : {
$nin : [ -51009, -51012, -51031, -51078 ]
}
}, {
property : "_ProjectHierarchy",
value : window.projectId
}, {
property : "AcceptedDate",
value : {
$gt : Ext.Date.format(monthBack, 'Y-m-d')
}
}, {
property : "_ValidTo",
value : {
$gt : '3000-01-01'
}
} ]
Filter for second query:
filters : [ {
property : "_TypeHierarchy",
value : {
$nin : [ -51009, -51012, -51031, -51078 ]
}
}, {
property : "_ProjectHierarchy",
value : window.projectId
}, {
property : "ObjectID",
value : {
$in : window.objectIds
}
}, {
property : "c_Kanban",
value : {
$exists : true
}
} ]
Here's an alternative query that will return only the snapshots that represent transition into the Accepted state.
find:{
_TypeHierarchy: { $in : [ -51038, -51006 ] },
_ProjectHierarchy: 999999,
ScheduleState: { $gte: "Accepted" },
"_PreviousValues.ScheduleState": {$lt: "Accepted", $exists: true},
AcceptedDate: { $gte: "2014-02-01TZ" }
}
A second query is still required if you need the full history of the stories/defects. This should at least give you a cleaner initial list. Also note that Project: 999999 limits to the given project, while _ProjectHierarchy finds stories/defects in the child projects, as well.
In case you are interested, the query is similar to scenario #5 in the Lookback API documentation at https://rally1.rallydev.com/analytics/doc/.
If I understand the question, you want to get stories that are currently accepted, but you want that the returned results include snapshots from the time when they were not accepted. Before you write code, you may test an equivalent query in the browser and see if the results look as expected.
Here is an example - you will have to change OIDs.
https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/12352608129/artifact/snapshot/query.js?find={"_ProjectHierarchy":12352608219,"_TypeHierarchy":"HierarchicalRequirement","ScheduleState":"Accepted",_ValidFrom:{$gte: "2013-11-01",$lt: "2014-01-01"}}},sort:[{"ObjectID": 1},{_ValidFrom: 1}]&fields=["Name","ScheduleState","PlanEstimate"]&hydrate=["ScheduleState"]
You are correct that a query like this: find={"AcceptedDate":{$gt:"2014-01-01T00:00:00.000Z"}}
will return one snapshot per story that satisfies it.
https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/12352608129/artifact/snapshot/query.js?find={"AcceptedDate":{$gt:"2014-01-01T00:00:00.000Z"}}&fields=true&start=0&pagesize=1000
but a query like this: find={"ObjectID":{$in:[16483705391,16437964257,14943067452]}}
will return the whole history of the 3 artifacts:
https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/12352608129/artifact/snapshot/query.js?find={"ObjectID":{$in:[16483705391,16437964257,14943067452]}}&fields=true&start=0&pagesize=1000
To illustrate, here are some numbers: the last query returns 17 results for me. I check each story's revision history, and the number of revisions per story are 5, 5, 7 respectively, sum of which is equal to the total result count returned by the query.
On the other hand the number of stories that meet find={"AcceptedDate":{$gt:"2014-01-01T00:00:00.000Z"}} is 13. And the query based on the accepted date returns 13 results, one snapshot per story.