We are using the Datatables ultimate date/time sorting plugin (https://datatables.net/blog/2014-12-18) to try and sort date columns, but not having any luck getting it to properly sort dates in the right format. When the page loads, the following script is run:
//sets the date format for datatables for sorting purposes
//reference: https://datatables.net/blog/2014-12-18
$.fn.dataTable.moment( 'M/D/YYYY' );
/* Datatables */
$('.datatable').DataTable({
language : {
search : "_INPUT_",
searchPlaceholder : "Search...",
paginate : {
"next" : '<i class="fa fa-chevron-right"></i>',
"previous" : '<i class="fa fa-chevron-left"></i>'
}
},
responsive : {
details : {
display : $.fn.dataTable.Responsive.display.childRowImmediate,
type : 'column'
}
},
order : [0, 'desc'],
//date sorting
columnDefs:
{
targets: 'date_sortable',
render: function ( data, type, full, meta ) {
if(type === 'display'){
if(data){
var mDate = moment(data);
data = (mDate && mDate.isValid()) ? mDate.format("M/D/YYYY") : "";
console.log('rewrote data to ' + data);
}
}
console.log('date_sortable rendered');
return data;
}
}
});
According to both the Datatables documentation and the details I found on this SO post (DataTables Ultimate date / time sorting plug-in not working with Intl formats), I added date_sortable as a class name on the <th /> element in my HTML, but it looks like the render function isn't called, as my console.log[...] entries never run. I can see in the generated HTML the class is on my <th /> element, and the dates being shown are in the proper format ('n/j/Y', in PHP) so I'm at a total loss.
Everything looks setup correctly, so any tips/pointers here? The date ordering seems to be rather random in nature, with entries that have dates such as 1/6/2016 showing up in the middle (see screenshot), which makes no sense at all.
I will say this table is showing ~2,055 records so is it possibly a performance thing? This isn't currently loading with API calls, so all records are in the generated HTML as a single file.
can you look at the unshifted Function in Datatables?
// Add type detection
types.detect.unshift( function ( d ) {
return moment( d, format, locale, true ).isValid() ?
'moment-'+format :
null;
} );
if it's the case, you should use this:
$.fn.dataTable.moment('YYYY-M-D');
Please try this fiddle (this works with your date format):
`http://jsfiddle.net/Marouen/9qdj53am`
Hope this will help.
Related
I am using jquery plugin DataTables for building nice table
var table = $('#example').DataTable({
"data": source
});
I would like that make an each for all rows in table
Unfortunately this way may be out of date and does't work with new version (it launchs an error)
$(table.fnGetNodes()).each(function () {
});
And this way only works only for visibles rows (10 first rows because other rows are paginated)
table.each( function ( value, index ) {
console.log( 'Data in index: '+index+' is: '+value );
} );
Do you known how to loop to all rows please?
I finally found:
var data = table.rows().data();
data.each(function (value, index) {
console.log(`For index ${index}, data value is ${value}`);
});
Datatables have an iterator for each row rows().every() with this referring to the context of the current row being iterated.
tableName.rows().every(function(){
console.log(this.data());
});
If you are using the legacy DataTables then you can get all the rows even the paginated ones, as shown below...
table.fnGetNodes(); // table is the datatables object.
So we can loop through the rows by using .each() method provided by jQuery.
jQuery(table.fnGetNodes()).each(function () {
// You can use `jQuery(this).` to access each row, and process it further.
});
for example, this data has three fields UserID, UserName and isActive and we want to show only active users
The following code will return all the rows.
var data = $('#myDataTable').DataTable().rows().data();
We will print only active users
data.each(function (value, index) {
if (value.isActive)
{
console.log(value.UserID);
console.log(value.UserName);
}
});
I am trying to sort the data in the table using tablesorting plugin but the data has commas(,) as the separator so it is not sorting properly. I think it is considering the number as a string. With the help of google, I have found some codes but those are not working for me. Here is what I have tried so far.
$(document).ready(function(){
jQuery.tablesorter.addParser({
id: "fancyNumber",
is: function(s) {
return /^[0-9]?[0-9,\.]*$/.test(s);
},
format: function(s) {
return jQuery.tablesorter.formatFloat( s.replace(/,/g,'') );
},
type: "numeric"
});
$("#myTable").tablesorter({
widgets : ['zebra']
});
});
Please tell me what I am doing wrong.
I have given class <th width="62" class="{sorter: 'fancyNumber'}">column</th> to the column also.
If you set the sorter in the class name like this:
<th width="62" class="{sorter: 'fancyNumber'}">column</th>
Make sure you are also loading in the metadata addon because that is needed to process that format.
Or, if you don't want to use that plugin, you can set the parser using the headers option:
$(function(){
$('table').tablesorter({
headers : {
0 : { sorter: 'fancyNumber' }
}
});
});
I am using Jquery-option-tree plugin on a standalone website not based on Wordpress as in example 7 on the demo page, except that I am not passing a .txt file but a PHP page is generating the array of < options > to be passed to the plugin.
http://kotowicz.net/jquery-option-tree/demo/demo.html
This perfectly works: so let's say that the user wants to select a category for a new product, the plugin suits the purpose generating a nice: " Food -> fruit -> apples " upon user clicks. (see demo page ex. 7)
What instead if a product already exists with its categories assigned? I want to show it to the user when he edit that product, preloading the tree.
I have the ids path coming from database, so it would just be a matter of having the plugin to run without the user interact, using the value I pass. I saw this question: jQuery simulate click event on select option
and tried to simulate user' click with this (and other) methods with no luck.
$('#select')
.val(value)
.trigger('click');
Here the call to the function:
$(function() {
var options = {
empty_value: '',
set_value_on: 'each',
indexed: true, // the data in tree is indexed by values (ids), not by labels
on_each_change: '/js/jquery-option-tree/get-subtree.php', // this file will be called with 'id' parameter, JSON data must be returned
choose: function(level) {
return 'Choose level ' + level;
},
loading_image: '/js/jquery-option-tree/ajax-load.gif',
show_multiple: 10, // if true - will set the size to show all options
choose: ''
};
$.getJSON('/js/jquery-option-tree/get-subtree.php', function(tree) { // initialize the tree by loading the file first
$('input[name=parent_category_id]').optionTree(tree, options);
});
});
Here you can see the plugin:
https://code.google.com/p/jquery-option-tree/
I don't know that plugin, but looking at the examples there seems to be one that fits your need; Example 6 - AJAX lazy loading & setting value on each level change.
This would, in theory, just require some config options:
preselect: {'demo6': ['220','226']}, // array of default values - if on any level option value will be in this list, it will be selected
preselect_only_once: true, // prevent auto selecting whole branch when user maniputales one of branch levels
get_parent_value_if_empty: true,
attr: "id" // we'll use input id instead of name
If this doesn't fit you need though, you could initiate it from an event, like change, keyup, etc.
$(document).on('change', '#select', function() {
$('#nextSelect').val($(this).val());
})
$(document).on('change', '#nextSelect', function() {
$('#finalInput').val($(this).val());
})
Yes, you are right Mackan ! I saw that "preselect" option but I was initially unable to use it transferring the path from database to javascript, I ended up with my "newbie" solution to match the syntax:
preselect: {'parent_category_id': [0,'2','22']},
PHP
$category_path comes from DB query and is like "0,2,76,140,"
$path = explode(',', $category_path);
$preselect="";
foreach ($path as $value) {
$int = (int)$value;
if ($int != 0) $preselect.= "'". $int ."',";
else $preselect.= $int.","; // have to do this as ZERO in my case has to be without apostrophes ''
}
$preselect = "{'parent_category_id':[".$preselect."]}"
JS
var presel= <?php echo($preselect); ?>;
var options = {
preselect: (presel),
}
Any suggestion for a better code ?
Thanks a lot !!
I got problem with my data table sorting in the currency tab. when i try to sort the currency/price column..
Ex
A - $ 10,0000
B - $ 4,000
C - $ 8,000
In Chrome:
it works fine it displays the correct answer. which is BCA Ascending Order.
In Mozilla and IE:
it doesn't display the correct answer instead it will display this answer ACB Ascending order. I believe it reads the second lowest number since moz and iE reads the $ sign as a part of the string.
Any solution for this?
you may try this sample link that I found
open it in Chrome and Mozilla
I just solve my problem.
Instead of creating a extended .js file for the currency plugin which causes error.. I write code together with the creating the datatable object. something like this:
$(document).ready(function(){
model_select();
$('.data_table').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bRetrieve":true,
"aoColumnDefs": [
{ "sType": "currency", "aTargets": [ 10 ] }
]
});
// Change this list to the valid characters you want
var validChars = "$£€c0123456789-,";
// Init the regex just once for speed - it is "closure locked"
var str = jQuery.fn.dataTableExt.oApi._fnEscapeRegex("$£€c0123456789-,");
var re = new RegExp('[^'+str+']');
jQuery.fn.dataTableExt.aTypes.unshift(
function ( data )
{
if ( typeof data !== 'string' || re.test(data) ) {
return null;
}
return 'currency';
}
);
});
How to disable previous days in default DHTML calendar?
I used the following code,
<script type="text/javascript">
Calendar.setup({
inputField : '_dob',
ifFormat : '%m/%e/%y',
button : '_dob_trig',
align : 'Bl',
singleClick : true,
disableFunc: function(date) {
var now= new Date();
return (date.getTime() < now.getTime());
}
});
</script>
It works in disabling the previous dates. But when we select on valid date, nothing happens. The date is not being added to the text filed of calendar.
If I changes the month and comes back , I can select date!
Any Idea?
Wow!
It might be some javascript error. I was unable to select any dates unless going and coming back from next month...
I past it by giving some if loops. My updated code is below.
<script type="text/javascript">
Calendar.setup({
inputField : '_dob',
ifFormat : '%m/%e/%y',
button : '_dob_trig',
align : 'Bl',
singleClick : true,
disableFunc: function(date) {
var now= new Date();
if(date.getFullYear()<now.getFullYear())
{
return true;
}
if(date.getFullYear()==now.getFullYear())
{
if(date.getMonth()<now.getMonth())
{
return true;
}
}
if(date.getMonth()==now.getMonth())
{
if(date.getDate()<now.getDate())
{
return true;
}
}
},
});
</script>
Greetings to everyone replied...
I had the same problem, and after debugging it, the problem seems to be that the calendar can't figure out what the current calendar date should be (because it's disabled by the disableFunc callback function). You have two options available.
Make sure the disableFunc function returns false for the current date. This way it won't be disabled in the calendar, and it'll function properly.
You can add the following lines in the calendar.js, after the if (!cell.disabled) line. (that happens to be line 1183 in my version of the file - v 1.51)
else
{
this.currentDateEl = cell;
}
The second option will allow you to disable the current date as well.
For those wondering what this DHTML calendar is, here is a link to it's docs: http://www.dni.ru/js/doc/html/reference.html
Disable Function should return TRUE or FALSE always.
disableFunc function: A function that receives a JS Date object. It should return true if that date has to be disabled, false otherwise. DEPRECATED (see below).
Please refer the following,
DHTML CALENDAR SETTINGS REFERENCE
But in your code disable function returns nothing... :( so it goes into js error and nothing works on event click..
check your condition,
return (date.getDate() <= now.getDate());
Return true or false according to your requirement after checking the above condition...
try the code below
Calendar.setup({
inputField : '_dob',
ifFormat : '%m/%e/%y',
button : '_dob_trig',
align : 'Bl',
singleClick : true,
dateStatusFunc : function (date) {
var now= new Date();
return (date.getDate() <= now.getDate());
}
});