The first column of a table has its rank in the current sort order. I update it after sorting (easy) but cannot figure out how to access the current page # and size of page to update it for the 2nd, 3rd, etc page. I have..
$("table.datatable")
.dataTable({
fnDrawCallback: function() {
$(this).find("td.counter span").each(function(i, row) {
$(this).html(i + 1);
// Should be something like
// $(this).html(dataTable.pageno + dataTable.pagesize + i)
});
}
});
What's the proper way of getting the page # and page size to do that so the first row on the second page is #11 (if it's 10 per page)?
UPDATE ended up doing this; not sure how "proper" it is, but..
fnDrawCallback: function(settings) {
$(this).find("td.counter span").each(function(i, row) {
$(this).html(i + 1 + settings._iDisplayStart);
});
}
You can use this example on the Datatables documentation, which adds an index column to your table:
http://datatables.net/release-datatables/examples/api/counter_column.html
Related
I am sorting my tablesorter table successfully from a link outside the table, using var sorting = [[2,"n"]];. Clicking that link does sort the table the opposite way (from ASC to DESC, for example).
How can I sort the table by the 3rd column ascending, without losing the ability to sort in the opposite direction by clicking the link again? var sorting = [[2,"a"]]; does sort the table ascending, but I cannot click that link again to sort in the opposite direction!
Thanks for your help!
These are my lines:
$("#trigger-tg").click(function() {
// set sorting column and direction, this will sort on the first and third column the column index starts at zero
var sorting = [[2,"n"]];
// sort on the first column
$("table").trigger("sorton",[sorting]);
// return false to stop default link action
return false;
});
The tablesorter link in your question is pointing to the original tablesorter, but the code links and example are from my fork of tablesorter which does include the ability to pass an "n" to sort the column in the "next" direction.
The code example you shared does work - see demo.
$(function() {
var $table = $("table");
$table.tablesorter();
$("#trigger-tg").click(function() {
$table.trigger("sorton", [[[2, "n"]]]);
return false;
});
});
Here is the documentation page showing all possible settings - https://mottie.github.io/tablesorter/docs/example-trigger-sort.html
If you must use the original tablesorter, try the code from this demo.
Update: To notify the user that additional clicks will change the sort, try this code (demo)
HTML
<p>Sort Animals column from <a id="trigger-tg" href="#">A-Z</a>.</p>
Script
$(function() {
var $table = $("table"),
targetColumn = 2;
$table
.on("sortEnd", function() {
var c = this.config;
if (c.sortList[0][0] === targetColumn) {
$("#trigger-tg").text(c.sortList[0][1] === 0 ? "Z-A" : "A-Z");
}
})
.tablesorter();
$("#trigger-tg").click(function() {
$table.trigger("sorton", [[[targetColumn, "n"]]]);
return false;
});
});
I'm using the DataTables library to create a table with extra functionality. What I'd like to achieve, is that the user can select rows and then press a button. This will call the server, do some stuff and the rows should be updated accordingly.
However, after I'm done iterating over the rows to be changed and setting its values, re-drawing the table does not actually update its values. I update the data object, invalidate the cache and call table.draw(). It's very similar to the last example on this page.
I have created a JSFiddle of this issue. The button updates the date objects of the selected rows and the table is re-drawn, but the data inside the table is not updated. The core JS code:
$('#updateRow').click(function() {
//Get the table
var table = $('#example').DataTable();
//Iterate over selected rows
var rowData = table.rows({
selected: true
}).every(function() {
//For every selected row, update startDate
var d = this.data();
d.startDate = "01/01/2017";
console.log('Set startDate of ' + d.name + ' to ' + d.startDate);
//Invalidate the cache
this.invalidate();
});
//Re-draw the table
table.draw();
});
I forked and did the solution from your JsFiddle. Here's the relevant snippet from fiddle https://jsfiddle.net/k38r9be5/1/
var rowData = table.rows({
selected: true
}).every(function(rowIdx) {
var colIdx = 4; // startDate is the fifth column, or "4" from 0-base (0,1,2,3,4...)
table.cell( rowIdx, colIdx).data('01/01/2017').draw();
});
Basically, via the API you can get the cell object itself, and modify the contents with .data(). In your version you weren't actually getting a particular cell object and instead just copied the data contents of the row to a variable, and modified that.
I have 2 tables that are using DataTable jQuery Plug-in.
I wondering if there is a way to hide my pagination on the bottom right of my table.
Note:
Only show the pagination when I need one.
Hide the pagination when the query results is less than 10.
Use drawCallback option to handle DT draw event and show/hide pagination control based on available pages:
$('#table_id').dataTable({
drawCallback: function(settings) {
var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
pagination.toggle(this.api().page.info().pages > 1);
}
})
$('#dataTable_ListeUser').DataTable( {
//usual pager parameters//
"drawCallback": function ( settings ) {
/*show pager if only necessary
console.log(this.fnSettings());*/
if (Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength) > 1) {
$('#dataTable_ListeUser_paginate').css("display", "block");
} else {
$('#dataTable_ListeUser_paginate').css("display", "none");
}
}
});
Use 'drawCallback' to solve this problem.
1.On the webpage, use developer tool to inspect the 'previous' button, then you will find a div element that wraps both the 'previous' and 'next' buttons. DataTables automatically assigned an id to this div based on your html table element's id.
For example, I have a table with id 'Atable'. In this table, DataTables automatically created a div element with id called 'Atable_paginate' to wrap the previous and next buttons.
2.For drawCallback, we write a function which checks if there is less than 1 page, if so, we hide element by utilising id.
For example, you have set there are 20 records on one page by
pageLength: 20,
which means if there are less then 20 records, we don't need to display 'previous' and 'next' buttons. So we write like below,
drawCallback: function(settings){
if($(this).find('tbody tr').length <= 20){
$('#Atable_paginate').hide();
}
}
3.The initialization of Atable should be like below
var table = $('#Atable').DataTable({
pageLength: 20,
lengthChange: false,
drawCallback: function(settings){
if($(this).find('tbody tr').length <= 20){
$('#Atable_paginate').hide();
}
}
});
4.If there are more than one table on the webpage, apply this method on each table.
You can use fnDrawCallback() method to hide the pagination in dataTable.
var oTable = $('#datatable_sample').dataTable({
"iDisplayLength": 10,
"fnDrawCallback": function(oSettings) {
if ($('#datatable_sample tr').length < 10) {
$('.dataTables_paginate').hide();
}
}
});
The length which you can define as per the row you want to display in the listing.
$(this) did not work for me, probably because I am using TypeScript. So I used a different approach to get the JQuery element for the table wrapper and the DataTables API. This has been inspired by the answer of BitOfUniverse and tested with DataTables 1.10.
TypeScript:
'drawCallback': (settings: any) => {
// hide pager and info if the table has NO results
const api = new $.fn.dataTable.Api(settings);
const pageCount = api.page.info().pages;
const wrapper = $('#' + settings.sTableId).closest('.dataTables_wrapper');
const pagination = wrapper.find('.dataTables_paginate');
const info = wrapper.find('.dataTables_info');
pagination.toggle(pageCount > 0);
info.toggle(pageCount > 0);
}
You can give options when you create your datables on Javascript
$('.examples').DataTable({
"paging": false
});
All options are listed here:
http://www.datatables.net/reference/option/
I have an sortable grid of elements, that updates its value to DB after user moves the element. The problem is, I don't know how to update the id of all previous elements to a new one without reloading the page.
In PHP, I would do something like this (code from FAQ of one of my older pages), but I can't use PHP (it has to happen without any page reloading, right after user places element he moved):
if ($old_order > $order){
$result = dbquery("UPDATE faq SET orders=orders+1 WHERE orders>='$order' AND orders<='$old_order'");
}else{
$result = dbquery("UPDATE faq SET orders=orders-1 WHERE orders>='$old_order' AND orders<='$order'");
}
I would like to do that with jQuery, basically I have 7 elements with id from 0 to 6 and every time user changes the position, I serialize it and send it with ajax to an php code that saves it.
What it does now:
Move elemtent 1 to position 4.
Saves and works.
Move element 3 to position 2
Moves element 1 from position 4 back to his old one, as the ID of it
is still 1 and not 4.
What I want to do:
Move element 1 to position 4
Change ID of element 1 from 1 to 4
Change ID of element 2, 3 and 4 by -1 to id 1, 2 and 3
I hope somebody understands me and can help me.
jQuery code I actauly use:
$(".content-page").sortable({
start: function(e,ui){
ui.placeholder.height($(".sorted-icons").outerHeight(true));
ui.placeholder.width($(".sorted-icons").outerWidth(true));
},
placeholder: 'placeholder',
items: '.sorted-icons:not(.new_icon)',
update: function(e,ui) {
var order = $(this).sortable("serialize") + '&order=icons' + '&content_id=' + $(this).attr("data-shortcut-id");
console.log(order);
$.post("page_ajax.php", order).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
});
}
}).disableSelection();
Html code basically looks like this with content inside of that div thats irelevant:
echo "<div class='sorted-icons' id='icon_$id'>";
If you have any questions, just comment and Ill try to answer them and update the queston.
Fixed jQuery:
var i = 0;
$(this).children('.sorted-icons').each(function(){
$(this).attr('id', 'icon_' + i);
i++;
});
Still have problem with PHP part tho. Its saving them in weird orders.
Ok, so I had one little bug in my PHP code, but I managed to fix the jQuery with really simple pice of code:
$(".content-page").sortable({
start: function(e,ui){
ui.placeholder.height($(".sorted-icons").outerHeight(true));
ui.placeholder.width($(".sorted-icons").outerWidth(true));
},
placeholder: 'placeholder',
items: '.sorted-icons:not(.new_icon)',
update: function(e,ui) {
var order = $(this).sortable("serialize") + '&order=icons' + '&content_id=' + $(this).attr("data-shortcut-id");
console.log(order);
$.post("page_ajax.php", order);
// THIS PART //
var i = 0;
$(this).children('.sorted-icons').each(function(){
$(this).attr('id', 'icon_' + i);
i++;
});
// THIS PART //
}
}).disableSelection();
Hopefully might help somebody else.
I'm using jquery tablesorter to sort my table. I've tried to google my question, didn't find what I was looking for.
I've got a table which content changes dynamically so I want to change the way items are sorted.
One case I've got table populated with text which can be sorter with default .tablesorter() and I've got another case where digits are in table so I need to invoke tablesorter like this :
$('table').tablesorter({
headers : {
0 : {sorter:'digit'},
1 : {sorter:'digit'},
2 : {sorter:'digit'},
3 : {sorter:'digit'}
}
});
I have a method that does reload to table switching between numbers/text in table content, how can I change the way table is sorted.
In the example (pseudocode):
function reloadTableData
if table contains numbers user this tablesorter (I have a way to know if table contains numbers)
$('table').tablesorter({
headers : {
0 : {sorter:'digit'},
1 : {sorter:'digit'},
2 : {sorter:'digit'},
3 : {sorter:'digit'}
}
});
if table contains text use ordinary table sorter
$('table').tablesorter();
end
I can reload table data n times with either text/numbers.
I've tried the following :
function initTablesorter(n) {
switch(n)
{
case "number":
digitTableSorter();
break;
case "text":
defaultTableSorter();
break;
default:
}
}
function digitTableSorter(){
$('table').tablesorter({
headers : {
0 : {sorter:'digit'},
1 : {sorter:'digit'},
2 : {sorter:'digit'},
3 : {sorter:'digit'}
}
});
}
function defaultTableSorter(){
$('table').tablesorter();
}
Needless to say it's not working, I hope someone did something like this before, I'm stuck for some time now.
So is it not working because you are reinitialising tablesorter on a table? You may try to unbind tablesorter before rebinding it.
$('table')
.unbind('appendCache applyWidgetId applyWidgets sorton update updateCell')
.removeClass('tablesorter')
.find('thead th')
.unbind('click mousedown')
.removeClass('header headerSortDown headerSortUp');
Have a look at Remove jQuery tablesorter from table.
I think you are looking for this - You will need MetatData plugin to get the th classes to like "{sorter: 'digit'}"
http://tablesorter.com/docs/example-trigger-sort.html
$("#trigger-link").click(function() {
// set sorting column and direction, this will sort on the first and third column the column index starts at zero
var sorting = [[0,0],[2,0]];
// sort on the first column
$("table").trigger("sorton",[sorting]);
// return false to stop default link action
return false;
});