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' }
}
});
});
Related
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.
I have made an inline datepicker, i only got 1 issue.
I can't implement the beforeShowDay option
i use PHP to load an array out of a database. I implement this with AJAX
code:
$(document).ready(function() {
var ajax = $.ajax({
url : "dates.php",
data : "action=showdates",
dataType : "json"
});
ajax.complete(function(calendarEvents) {
$("#inline").datepicker({
beforeShowDay : ShowDay()
});
function ShowDay(date) {
console.log('function showday');
for (var i = 0; i < calendarEvents.length; i++) {
var jaar = calendarEvents[i].slice(0,4);
console.log(jaar);
}
console.log('showday');
}
});
});
the trouble i have atm is that i want to have appointment on certain days.
i would ike to use the return [true, "classname", ""] for dates with an appointment, and return [true, "", ""] for all the other dates. i hope i can get some help!
This is what i am trying to do: http://www.emirplicanic.com/javascript/jquery-ui-highlight-multiple-dates-in-jquery-datepicker
the problem is that my datepicker is inline so i cant directly implement into the beforeShowDay: function(date) {
}
Pls post a demo on jsfiddle or something like that, it would be appreciated =D
*btw i tried to give beforeShowDay: ShowDay but this doesn't call the function
Alright i fixed it it was really easy XD, i had and old version of bootstrap datepicker. This version didnt support BeforeShowDay! I now got a newer version and it all works!
Consider "Method A: no ajax":
$(function() {
var emails = [
"john#beatles.com",
"george#beatles.com",
"paul#beatles.com",
"ringo#beatles.com"
];
$( "#invitees" ).autocomplete({
source:emails
});
});
This is given a relatively small, "unfiltered" array. The autocomplete function filters it for you as you type. I want to fetch this data once, thereby only requiring one call to the database.
Consider "Method B: 'internal' URL:
$( "#invitees" ).autocomplete({
source:"/api/get/users"
});
This does not work as I expect it to. No matter what I type, the entire list is always there. Now, after research reading the docs, other S/O questions, and every example I can find- they usually conclude with something like this:
"Data should be filtered server side. The autocomplete widget adds the term parameter to the url, so the resulting url is something like: /search.php?term=whatityped
I can handle that, but that's not totally happening in "Method A", is it? For larger data sets, I get it: no need to pre-load 100,000 results. But in this case, I want the ability to run one query and be done with it. That way if a mobile user is standing in the desert with "one bar" of service, his phone won't lock up while the server repeatedly requests new data every time he types a letter, right?
When the request goes to the internal URL:'/api/get/users'... here's the relevant part of the PHP code:
function get($className,$param1="all",$param2=""){
//above parameters will be refactored...
$stmt=$this->db->prepare('SELECT username FROM users');
$stmt->execute();
$this->data=$stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($this->data);
}
That function returns:
["john#beatles.com","george#beatles.com","paul#beatles.com","ringo#beatles.com"]
So again, If I explicitly do this, the filtering works:
var emails = [
"john#beatles.com",
"george#beatles.com",
"paul#beatles.com",
"ringo#beatles.com"
];
$( "#invitees" ).autocomplete({
source:emails
});
but this does not:
$( "#invitees" ).autocomplete({
source:"/api/get/users"
});
What am I missing here?
PS: Here is an unpolished attempt at method C, by the way- "ajax callback":
(Note: it's meant to accept an associative array from PHP, but the point is that it also does not "self-filter")
$( "#invitees" ).autocomplete({
source: function(request,response){
$.ajax({
url:"/api/get/users",
dataType:"json",
data:{
maxRows:5, // ? does not work
//name_startsWith: request.term // ? does not work
},
error: function(xhr,status){
alert(status);
},
success: function (data){
// alert(data);
response($.map(data,function (item){
return{
label: item.username,
};
}));
}
});
}
});
//ensures autocomplete is not set to "off"
$('input[name=invitees]').attr('autocomplete','on');
For completeness, here's My HTML:
<label for="invitees">Invite by email: </label>
<input id="invitees" name="invitees"/>
You can put the autocomplete function inside a callback function and pass the return data into that.
An example:
$.getJSON('/myJSONdata', function(data) {
$( "#input_field" ).autocomplete({
source: data
});
});
This will assign the autocomplete function to the desired fields after the callback is complete and the data would be assigned just as if it were plain text written into the function.
The autocomplete function obviously won't work until the callback completes successfully so that is something that you might want to keep in mind.
Here's the most basic code of it (i'm using this)
$("form").relatedSelects({
onChangeLoad: 'datasupplier.php',
selects: ['stateID', 'countyID', 'townID', 'villageID']
});
i need to pass several more parameter for some reason. my usual ajax code is something like this
$.post("ajax/template.php", {myparams: $("#myparams").val(), action: "SEARCH_MEMBER_DETAILS" },
function (data){
var returnCode = data.returnCode;
if (returnCode == "1"){
$("#data").val(data.name);
}
},"json");
question is, how do I send the params like myparams and action to the jQuery Related Selects code?
i tried something like
$("form").relatedSelects({
onChangeLoad: 'datasupplier.php',
data: {action: "SEARCH_MEMBER_DETAILS"},
selects: ['stateID', 'countyID', 'townID', 'villageID']
});
but it seems the additional params are not sent
The relatedScripts plugin does not provide any facility to manipulate the ajax request.
But it is possible to alter it slightly to achieve the requirement.
If you are ready to make a change in the plugin do the following steps
In the populate($caller,$select,o) method of the plugin make the following change
beforeSend: function(){
return o.onLoadingStart.apply($select, Array.prototype.slice.call(arguments,0));
},
It is now beforeSend: function(){ o.onLoadingStart.call($select); },
Then change your script like
$("#example-2").relatedSelects({
onChangeLoad : 'datasupplier.php',
loadingMessage : 'Please wait',
selects : ['stateID', 'countyID', 'townID', 'villageID'],
onLoadingStart : function(jqxhr, settings) {
console.log('st', arguments, settings.url);
settings.url += '&t=tttt'
}
});
Demo: Fiddle
I've went through the documentation of the plugin and seems that there's not a way to achieve what you need.
If you don't want to extend the plugin and implement the functionality by yourself, you can try by creating the parameter inside the onChangeLoad and pass them as GET parameter like this:
$("form").relatedSelects({
onChangeLoad: 'datasupplier.php?myparams='+$("myparams").val()+'&action=SEARCH_MEMBER_DETAILS',
selects: ['stateID', 'countyID', 'townID', 'villageID']
});
Hoping that using something like this demo it is possible to drag items within and between two columns, and update their order either live or with a "save" button to MySQL. Point being that you can make changes and return to the page later to view or update your ordering.
http://pilotmade.com/examples/draggable/
Doing it for just one column is fine, but when I try to pass the order of both columns, the issue seems to be passing multiple serialized arrays with jQuery to a PHP/MySQL update script.
Any insight would be much appreciated.
If you look below, I want to pass say...
sortable1entry_1 => 0entry_5 => 1
sortable2entry_3 => 0entry_2 => 1entry_4 => 2
EDIT: This ended up doing the trick
HTML
<ol id="sortable1"><li id="entry_####">blah</li></ol>
jQuery
<script type="text/javascript">
$(function()
{
$("#sortable1, #sortable2").sortable(
{
connectWith: '.connectedSortable',
update : function ()
{
$.ajax(
{
type: "POST",
url: "phpscript",
data:
{
sort1:$("#sortable1").sortable('serialize'),
sort2:$("#sortable2").sortable('serialize')
},
success: function(html)
{
$('.success').fadeIn(500);
$('.success').fadeOut(500);
}
});
}
}).disableSelection();
});
This is the PHP query
parse_str($_REQUEST['sort1'], $sort1);
foreach($sort1['entry'] as $key=>$value)
{
do stuff
}
what I would do is split them up
data :
{
sort1:$('#sortable1').sortable('serialize'),
sort2:$('#sortable2').sortable('serialize')
}
then when you post you can get the request and set them as needed, I hope that makes sense
so what I do is this
parse_str($_REQUEST['sort1'],$sort1);
foreach($sort1 as $key=>$value){
//do sutff;
}