I would like to use a pagination style for DataTable's that is mobile friendly, I'd just like a button to load more rows when clicked which will append rows under the current visible rows.
I know this isn't available as a default option in DataTables but I believe it shouldn't be to difficult to create. Has anyone created this pagination method or seen it in use on a DataTable's table?
If not how can I modify the code of my table at https://jsfiddle.net/6k0bshb6/16/ to use this pagination style to make my table mobile friendly.
// This function is for displaying data from HTML "data-child-value" tag in the Child Row.
function format(value) {
return '<div>Hidden Value: ' + value + '</div>';
}
// Initialization of dataTable and settings.
$(document).ready(function () {
var dataTable = $('#example').DataTable({
bLengthChange: false,
"pageLength": 5,
"pagingType": "simple",
"order": [[ 7, "asc" ]],
"columnDefs": [
{
"targets": [ 5 ],
"visible": false,
"searchable": true
},
{
"targets": [ 6 ],
"visible": false,
"searchable": true
},
{
"targets": [ 7 ],
"visible": false,
"searchable": true
}
],
// Dropdown filter function for dataTable from hidden column number 5 for filtering gifts.
initComplete: function () {
this.api().columns(5).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
// This function is for handling Child Rows.
$('#example').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = dataTable.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(tr.data('child-value'))).show();
tr.addClass('shown');
}
});
// Checkbox filter function below is for filtering hidden column 6 to show Free Handsets only.
$('#checkbox-filter').on('change', function() {
dataTable.draw();
});
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = '£0.00';
var position = data[6]; // use data for the position column
if($('#checkbox-filter').is(":checked")) {
if (target === position) {
return true;
}
return false;
}
return true;
}
);
});
UPDATE: I have found some information on how to do this on the DataTables website although I don't fully understand how to integrate it into my table.
https://datatables.net/forums/discussion/3920/twitter-facebook-style-pagination
What you could possibly do (I've not tried it, but I can't think of why it wouldn't work...) is to set the scroll loading gap (the number of pixels before the bottom of the scroll for when the new data is loaded) to a negative number ( http://datatables.net/usage/options#iScrollLoadGap ) and then add a little button at the bottom of the table (might need to use fnDrawCallback for that) which when clicked will load the next data set (fnPageChange('next') should do that).
Anyone know how I can make this work with my table? Could someone show me how to do this on jsfiddle?
UPDATE 2: Response from datatables admin https://datatables.net/forums/discussion/35148/load-more-style-twitter-style-pagination-custom#latest
The iScrollLoadGap option you mention isn't available in 1.10 -
infinite scrolling was removed in 1.10 and that option with it.
However the basic principle still remains - you can either have a
button the user needs to press to load more rows (either increase the
page size or use rows.add() to add more rows) or use a scroll
detection to do the same thing.
Allan
Solved..
<button id="button" type="button">Page +5</button>
//Alternative pagination
$('#button').on( 'click', function () {
var VisibleRows = $('#example>tbody>tr:visible').length;
var i = VisibleRows + 5;
dataTable.page.len( i ).draw();
} );
you could use something like:
$(window).on("swipeleft", $("#example_next").click());
$(window).on("swiperight", $("#example_previous").click());
it will only work on mobile and uses your existing functionality...
Related
I am using datatables and I am trying to add 'show/hide columns dynamically', from https://datatables.net/examples/api/show_hide.html
In my web page I already have the code this bit of code:
<script>
$(document).ready(function(){
var table = $('#example').DataTable();
//DataTable custom search field
$('#custom-filter').keyup( function() {
table.search( this.value ).draw();
} );
});
</script>
and now I want to add
$(document).ready(function() {
var table = $('#example').DataTable( {
"scrollY": "200px",
"paging": false
} );
$('a.toggle-vis').on( 'click', function (e) {
e.preventDefault();
// Get the column API object
var column = table.column( $(this).attr('data-column') );
// Toggle the visibility
column.visible( ! column.visible() );
} );
} );
But I get the error :
DataTables warning: table id=example - Cannot reinitialise DataTable.
I've tried to combine the two into one, but keep getting the error.
Any help would be appreciated.
How can I get my tooltip being displayed when using pagination within the datatable plugin?
I am using the plugin protip in connection with datatables to display tooltips, when text inside a column is too long. The tooltips plugin already works with the following snippet:
//Datatable Setup
jQuery(document).ready(function($) {
var table = $('#irp-table.raab').DataTable({
"columnDefs": [
{ visible: false, targets: 2 },
{ className: 'mdl-data-table__cell--non-numeric', targets: [0, 1]}
],
"order": [[ 0, 'asc' ]],
"displayLength": 25,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="3">'+group+'</td></tr>'
);
last = group;
}
} );
}
} );
//Initialize ToolTip
jQuery(document).ready(function($) {
$.protip();
});
//ToolTip hover behaviour
jQuery(document).ready(function($) {
$('td').bind('mouseenter', function () {
var $this = $(this);
if (this.offsetWidth < this.scrollWidth) {
var text = $this.text();
$this.attr("data-pt-title", text);
$this.protipShow()
}
}).mouseenter();
});
However it just works on the first site for the case I am using pagination on my datatable and navigate to another site.
SOLUTION
You need to use drawCallback to initialize tooltips every time DataTables redraws the table. This is needed because TR and TD elements for pages other than first are not present in DOM at the time first page is displayed.
Also the call to mouseenter() is not needed.
For example:
"drawCallback": function ( settings ) {
var api = this.api();
// ... skipped ...
$.protip();
$('td', api.table().container()).on('mouseenter', function () {
var $this = $(this);
if (this.offsetWidth < this.scrollWidth) {
var text = $this.text();
$this.attr("data-pt-title", text);
$this.protipShow();
}
});
}
LINKS
See jQuery DataTables: Custom control does not work on second page and after for more examples and details.
I have two questions for jquery datatables :
Is it possible to select the first row automatically when the DataTable is initialized?
At the moment it is possible, that the user deselect an item by clicking on it. I want, that at least one row keeps selected. When the user clicks to the selected row, the selection should not be removed.
This is my initialization of my DataTable:
ar dataTableOption = {"pageLength": 5,
"pagingType": "simple",
"info": false,
"searching": false,
"select": {
style: 'single'
},
"lengthChange": false,
"columnDefs": [
{
"targets": [0],
"visible": false,
"searchable": false
}
]
};
dataTable = $('#dataTable').DataTable(dataTableOption);
Thank you for your help in advance!
One of the ways:
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
if($(this).hasClass( "selected" )){
//make sure it can't be unselected if there is just one selected row
if(table.rows('.selected').data().length > 1){
$(this).removeClass( "selected" );}
}
else{
$(this).addClass( "selected" );
}
} );
//To pre-select the first row
$('#example tbody tr:eq(0)').click();
} );
Demo
# Harshul Pandav
Thank you for your post. Your proposed solution worked not 100% for me but it helped me a lot for finding a solution for my problems.
To select the first line worked this for me:
dataTable.row(':eq(0)', { page: 'current' }).select();
To get at least one line selected I use the user-select event, to remember my last selected column:
dataTable.on( 'user-select', function ( e, dt, type, indexes ) {
lastSelectedRow = dt.rows( '.selected' )[0][0];
});
After this, the click event passed through, if no row is selected anymore, the row with index of last selected row is selected:
dataTable.on( 'click', 'tr', function (evt) {
if (dataTable.rows( {selected:true} ).any() == false) {
dataTable.row(lastSelectedRow).select();
}
)};
For finding out the last selected row the deselect (dt.on( 'deselect', function ( e, dt, type, indexes ) ) event can also be used.
Prevent deselect of already-selected row:
myTable.on('user-select', function (e, dt, type, cell, originalEvent) {
if ($(cell.node()).parent().hasClass('selected')) {
e.preventDefault();
}
});
Ok so I have this datatable with around 90 fields being populated from a dbContext (Visual Studio MVC4). I added the .makeEditable() to enjoy inline editing...
Most of my fields are of a type string (but a user CAN input a date if he opts to....even though its a text type field, the date will be input as simple text..)
The problem I have is that even though I'm successfully being able to get the class of the edit form to become "datepicker", the calender isn't popping up and on other simple non-datatable pages, it runs just fine.
I want to be able to set certain column cells to have inline datepicking ability..
I want my table to look like this thing http://jquery-datatables-editable.googlecode.com/svn/trunk/inline-edit-extra.html
I tried mimic-ing the code there but with no success....its always a textbox for editing instead of a calender view..
UPDATE: I noticed that if I change the "type:" field in
$.fn.editable.defaults = {
name: 'value',
id: 'id',
type: 'datepicker',
width: 'auto',
height: 'auto',
event: 'click.editable',
onblur: 'cancel',
loadtype: 'GET',
loadtext: 'Loading...',
placeholder: 'Double-Click to edit',
loaddata: {},
submitdata: {},
ajaxoptions: {}
};
My entire table gets a datepicker on editing mode...
Apparently the intializing code to give certain columns datepicker options doesn't work as it should ....or at least I guess so
**UPDATE END****
This is my datatable initialization code:
<script language="javascript" type="text/javascript">
$(function() {
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
});
$(document).ready(function ()
{
$('#myDataTable thead tr#filterrow th').each(function () {
var title = $('#myDataTable thead th').eq($(this).index()).text();
$(this).html('<input type="text" onclick="stopPropagation(event);" placeholder="Search ' + title + '""style="direction: ltr; text-align:left;" />');
});
$("#myDataTable thead input").on('keyup change', function () {
table
.column($(this).parent().index() + ':visible')
.search(this.value)
.draw();
});
var table = $('#myDataTable').DataTable({
//"scrollY": "200",
"scroller": "true",
"deferRender": "true",
"orderCellsTop": "true",
"columnDefs": [
{ "visible": false, "targets": 1 },
{ "type": "datepicker", "aTargets": [6,7,8,9,10] },
{ 'sClass':"datepicker", "aTargets": [6, 7, 8, 9, 10] }
],
"order": [[1, 'asc']],
"displayLength": 25,
"drawCallback": function (settings)
{
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(1, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="88">' + group + '</td></tr>'
);
last = group;
}
});
},
"fndrawCallback": function (settings) {
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
}
});
// Apply the search
table.columns().every(function () {
var that = this;
$('input', this.header()).on('keyup change', function () {
that
.search(this.value)
.draw();
});
});
// Order by the grouping
$('#myDataTable tbody').on('click', 'tr.group', function () {
var currentOrder = table.order()[0];
if (currentOrder[0] === 1 && currentOrder[1] === 'asc') {
table.order([1, 'desc']).draw();
}
else {
table.order([1, 'asc']).draw();
}
});
//$('#myDataTable thead').append($('#myDataTable thead tr:eq(0)')[0]);
$('#myDataTable').dataTable().makeEditable({
"aoColumnDefs": [
{ "type": "hasDatepicker", "aTargets": 4 },
{ "sClass": "hasDatepicker", "aTargets": 4 }
]
});
});
function stopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
} else {
evt.cancelBubble = true;
}
}
this is the datepicker.js
// add :focus selector
jQuery.expr[':'].focus = function (elem) {
return elem === document.activeElement && (elem.type || elem.href);
};
$.editable.addInputType(' datepicker', {
/* create input element */
element: function (settings, original) {
var form = $(this),
input = $('class ="datepicker" <input />');
// input.attr('class', 'datepicker');
input.attr('autocomplete', 'off');
form.append(input);
return input;
},
/* attach jquery.ui.datepicker to the input element */
plugin: function (settings, original) {
var form = this,
input = form.find("input");
// Don't cancel inline editing onblur to allow clicking datepicker
settings.onblur = 'nothing';
datepicker = {
onSelect: function () {
// clicking specific day in the calendar should
// submit the form and close the input field
form.submit();
},
onClose: function () {
setTimeout(function () {
if (!input.is(':focus')) {
// input has NO focus after 150ms which means
// calendar was closed due to click outside of it
// so let's close the input field without saving
original.reset(form);
} else {
// input still HAS focus after 150ms which means
// calendar was closed due to Enter in the input field
// so lets submit the form and close the input field
form.submit();
}
// the delay is necessary; calendar must be already
// closed for the above :focus checking to work properly;
// without a delay the form is submitted in all scenarios, which is wrong
}, 150);
}
};
if (settings.datepicker) {
jQuery.extend(datepicker, settings.datepicker);
}
input.datepicker(datepicker);
}
});
So after a lot of trial and error.....
I manually input the type of each of my 90 columns, and it manually worked....columnDefs with targeting a list of columns is probably bugged as in jeditable.datepicker it doesn't parse a list of columns passedin the settings....
Hope this helps a lost soul later on...
As continuation to this question,
Myself added the toggle button to datatable toolbar dom element as
"dom": "T<'clear'><'row DatatableRow'<'col-xs-3'l><'col-xs-3'><'col-xs-3'<'#ToggleButton'>><'col-xs-3 text-right'f>r>t<'row DatatableRow'<'col-xs-3'i><'col-xs-3'><'col-xs-3'><'col-xs-3 text-right'p>>"
and button is added as
$("div#ToggleButton").html('<br/><button type="button" class="btn btn-primary btn-sm" id="ToggleColumns">Toggle</button>');
But in this case, the click function is not working?
It was not working because you were trying to bind a button that is not yet existed on DOM. And you are recreating the table to change the fixed column index. I cant say this is a good way but i couldnt find to change fixed column of rendered datatable on documentations.
but i fixed your fiddle on your way.
the idea is to bind the button on init of datatable right after adding the custom button html like.
$(document).ready(function () {
foo(2);
function foo(columnNumber) {
table = $('#example').on('init.dt', function () {
$("div#ToggleButton").html('<br/><button type="button" class="btn btn-primary btn-sm" id="ToggleColumns">Toggle</button>');
$('#ToggleColumns').click(function () {
table.destroy();
debugger;
if (columnNumber == 2) {
columnNumber = 0;
} else {
columnNumber = 2;
}
foo(columnNumber);
});
}).DataTable({
scrollY: "300px",
scrollX: true,
scrollCollapse: true,
paging: false,
"dom": "T<'clear'><'row DatatableRow'<'col-xs-3'l><'col-xs-3'><'col-xs-3'<'#ToggleButton'>><'col-xs-3 text-right'f>r>t<'row DatatableRow'<'col-xs-3'i><'col-xs-3'><'col-xs-3'><'col-xs-3 text-right'p>>",
});
new $.fn.dataTable.FixedColumns(table, {
leftColumns: columnNumber
// rightColumns: 1
});
}
});
If you can find a way to change the fixedColumn number...
$('#ToggleColumns').click(function () {
// replace the following codes with changing fixedColumn columns
table.destroy();
if (columnNumber == 2) {
columnNumber = 0;
} else {
columnNumber = 2;
}
foo(columnNumber);
});