Change the page length of each page in datatable - javascript

I have the below datatable on my jsp page for which I want to change the page length on each page.I have tried 3 approaches but the page length is not getting changed. I have used the "lengthChange" option as "true". But it is also not working
$(document).ready(
function() {
document.getElementById("invoiceResult").style.display="block";
dTable = $('#result').DataTable(
{
paging : true,
"lengthChange": true,
fixedHeader : true,
"scrollY" : 400,
"scrollX" : true,
"bJQueryUI" : true,
fixedColumns : true,
"pageLength" : 25,
"order" : [ [ 4, "desc" ] ],
"columnDefs" : [ {
"width" : "100px",
"targets" : 0
} ],
drawCallback: function(){
$('#result').margetable({
type: 2,
colindex: [0,1],
});
},
rowsGroup: [0,1]
});
//This method is called whenever the page is redrawn
$('#result').on( 'draw.dt', function () {
var info = table.page.info();
var currentPage = info.page + 1;
if(currentPage==2){
//approach 1:
$('#result').DataTable.page.len(80).draw();
//approach 2:
$('#result').DataTable.getPager().config.size = 80;
$('#result').DataTable.refresh();
//approach 3:
$('#result').DataTable({ pageLength: 80 });
}
});

I'm not sure about the issue you're having, but in my example (with your options) I went for the lengthChange approach, and it's working fine:
//var dataUrl = "https://my-json-server.typicode.com/SagnalracSO/repoJD/employees?_limit=7";
var dataUrl = "https://my-json-server.typicode.com/SagnalracSO/repoJD/employees";
var table = $('#example').DataTable({
ajax: {
url: dataUrl,
dataSrc: ''
},
lengthChange: true,
pageLength: 25,
scrollY : 400,
scrollX : true,
bJQueryUI : true,
fixedColumns : true,
order : [ [ 4, "desc" ] ],
columnDefs : [ {
width : "100px",
targets : 0
}],
drawCallback: function() {
$('#example').margetable({
type: 2,
colindex: [0,1]
});
},
rowsGroup: [0, 1],
columns: [
{ data: 'id' },
{ data: 'firstName' },
{ data: 'lastName' },
{ data: 'position' },
{ data: 'office' },
{ data: 'age' },
{ data: 'startDate' }
]
});
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://www.jqueryscript.net/demo/Merge-Cells-HTML-Table/jquery.table.marge.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start Date</th>
</tr>
</thead>
</table>
<br>

Related

DataTable rows aren't turning into hrefs

I created a table with DataTables and at first the document titles that were rendered (from a local JSON file) were wrapped around anchor tags and turned into hrefs. I made some changes to my DataTable initialization and added some new columns to my table, and those things might have prevented the doc titles from turning into hrefs. I'm not 100% sure.
Importing table data:
loadTableData() {
$.noConflict();
let tableRes = KMdocs.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name,
"Categories": obj.ResourceType.results.map(function(val) {
return val.Label;
}).join(";"),
"Blank": ""
}
});
}
Rendering table:
$('#km-table-id').DataTable({
columns: [
{ data: "Blank" },
{
data: "Titles",
columnDefs: [ // ----- I believe the issue is with this block
{
data: "Path",
ordering: true,
targets: [ 1 ],
render: function(data, type, row) {
return $('<a>')
.attr({target: "_blank", href: row.Path})
.text(data)
.wrap('<div></div>')
.parent()
.html();
},
targets: [1]
}
],
},
{
data: "Categories",
searchable: true,
targets: [ 2 ],
visible: false
},
{
data: "Blank"
}
],
data: tableRes,
language: { searchPlaceholder: "Search All Documents" },
lengthMenu: [ 10, 25, 50, 100, 250, 500 ],
order: [],
pageLength: 500,
paging: true,
pagingType: "full_numbers",
responsive: true,
scrollCollapse: true,
scrollXInner: true,
scrollY: 550,
sDom: '<"top">rt<"bottom"flp><"left">' // puts dropdown on bottom
});
HTML snippet:
<table id="km-table-id" class="cell-border display stripe-hover">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Categories</th>
<th>My Favorites</th>
</tr>
</thead>
<tbody></tbody>
</table>

How to reload function datatables with new parameter in ajax when Selected value in Dropdown

I've this https://jsfiddle.net/cubmf71z/44/ ..
I want to reload function data_list with new parameter in ajax in same function data_list when i'm select or unselect in multiple ajax :
$(".select2-multiple").on("select2:select", function (c) {
I was try $('#example').DataTable().ajax.reload(); isnt working . i dont know how to put it .
in html
<input type="text" id="type">
in js
(function($){
$('.select2-multiple').select2();
})(jQuery);
$(document).ready(function data_list() {
var type = $('#type').val();
var table = $('#example').DataTable( {
"scrollY": "200px",
"paging": true
/*"ajax": {
"url": "https://",
dataSrc: function ( json ) {
if ( json.status === 'failed' ) {
return [];
}
return json.data;
}
},
"columns": [
{ "data": "appl" },
{ "data": "BankDates" },
{ "data": "State" },
{ "data": "cash" },
{ "data": "cheque" }
],
columnDefs: [
{ width: 100, targets: 0 },
{ "className": "text-center", width: 100, targets: 1 },
{ "className": "text-center", width: 100, targets: 2 },
{ "className": "dt-body-right", width: 100, targets: 3 },
{ "className": "dt-body-right", width: 100, targets: 4 }
]
*/
} );
$(".select2-multiple").on("select2:select", function (c) {
c.preventDefault();
var datas = c.params.data.id;
alert(datas);
//-> i update here parameter type $('#type').val('bank_date');
//i want to call call/reload function data_list datatables with new ajax url and parameter
var column = table.column(datas);
column.visible( ! column.visible() );
});
$(".select2-multiple").on("select2:unselect", function (e) {
e.preventDefault();
var data = e.params.data.id;
alert(data);
var column = table.column(data);
column.visible( ! column.visible() );
});
} );
Maybe you know how to call the function with another way ? or i'm wrong to put it ?
Thanks!
<!--<!DOCTYPE html>-->
<html>
<head>
<title>Simple Client Side</title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script src="Scripts/blockui.js"></script>
<script>
$(document).ready(function () {
var table = $('#example').DataTable({
"processing": true,
"serverSide": false,
rowId: "employeeId",
"createdRow": function (row, data, dataIndex) { },
"columns": [
{ "data": "first_name" },
{ "data": "last_name"},
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
],
"select": "multi",
"lengthMenu": [5, [10, 15, 25, 50, -1], [5, 10, 15, 25, 50, "All"]],
"pageLength": 5,
"ajax": {
contentType: "application/json; charset=utf-8",
url: "wsSample.asmx/GetAllEmployees",
type: "Post",
data: function (parms) {
data = $("#selMy").val();
return parms
},
dataSrc: "d"
},
order: [[0, 'asc']]
});
$("#selMy").select2().change(function () {
table.ajax.reload();
})
});
</script>
</head>
<body>
<table class="display" id="example" cellspacing="0">
<thead>
<tr>
<th>First</th>
<th>Last</th>
<th>Position</th>
<th>Office</th>
<th>Phone</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr class="searchRow">
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Phone</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
<select id="selMy" style="width:200px" multiple><option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
</body>
</html>

Datatable return [Object Object] on index column

I'm using datatable to show data from controller (i'm using Codeigniter) and need to show number column on the left table column.
I have tried:
$(document).ready(function() {
$('#booking_table').dataTable( {
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth : true,
ajax: {
"url" : base_url+"book/ajax_history",
"type" : "POST",
data : function (d){
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [
{
data : "b.booking_id",
visible : false,
},
{ data : null}, //where i should put index number
{ data : 'b.booking_date', className : "hidden-xs"},
{ data : 'b.from_name', className : "hidden-xs"},
{ data : 'b.to_name'},
],
responsive: false
});
// reference the table in a variable
var table = $('#booking_table').DataTable();
table.on( 'order.dt search.dt', function () {
table.column(0, {
search:'applied',
order:'applied'
}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
My Table:
<table class="table table-condensed" id="booking_table">
<thead>
<tr>
<th class="hidden-xs">id</th>
<th>No</th>
<th class="hidden-xs">
Tanggal
</th>
<th class="hidden-xs">
Pengirim
</th>
<th>
Penerima
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Refer to this https://www.datatables.net/examples/api/counter_columns.html
but, it's not working. What am I doing wrong ?
Please try below mentioned solution. Hope this will help you. Actually you initialized datatable two times.
$(document).ready(function() {
var table = $('#booking_table').dataTable({
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth: true,
ajax: {
"url": base_url + "book/ajax_history",
"type": "POST",
data: function(d) {
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [{
data: "b.booking_id",
visible: false,
},
{
data: null
}, //where i should put index number
{
data: 'b.booking_date',
className: "hidden-xs"
},
{
data: 'b.from_name',
className: "hidden-xs"
},
{
data: 'b.to_name'
},
],
responsive: false
});
table.on('order.dt search.dt', function() {
table.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});

jQuery datatables TypeError: b is null

I am facing with a error fired by Firebug when using a jquery datatables plugin
The table is like this:
<table id="dt_cursuri" class="table table-striped table-bordered dTableR">
<thead>
<tr>
<th data-class="expand">Curs</th>
<th data-hide="phone,tablet" data-name="Assign">Domeniu</th>
<th>Tip</th>
<th>Data modif</th>
<th class="centered-cell">Actiuni</th>
</tr>
</thead>
<tbody>
<tr>
<td class="dataTables_empty" colspan="6">Fetching data from server</td>
</tr>
</tbody>
</table>
The datatables initialization:
var oTable;
var responsiveHelper = undefined;
var breakpointDefinition = {
tablet: 1024,
phone : 480
};
var oTable = $('#dt_cursuri');
oTable = $('#dt_cursuri').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sPaginationType": "bootstrap",
"sDom": "<'row'<'col-md-6'l><'col-md-6'f>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
"sAjaxSource": "view/cursuri/server_side.php",
autoWidth : false,
"fnPreDrawCallback": function () {
// Initialize the responsive datatables helper once.
if (!responsiveHelper) {
responsiveHelper = new ResponsiveDatatablesHelper(oTable, breakpointDefinition);
}
},
"fnDrawCallback" : function (oSettings) {
responsiveHelper.respond();
},
"fnRowCallback": function( nRow, aData ) {
responsiveHelper.createExpandIcon(nRow);
},
"aoColumns": [
//{ "sClass": "center", "bSortable": false, sWidth: '2%', "bVisible": false },
{ sWidth: '35%' },
{ sWidth: '25%' },
{ sWidth: '20%' },
{ sWidth: '10%' },
{ "sClass": "center", sWidth: '10%', "bSortable": false }
],
"aaSorting": [[2, 'asc']]
} );
The server side json file is working corectly. The same code is used in other tables that work perfect, but this one is not
Could someone help me?
The error is fired for this line from jquery.datatables.js:
!a.sLoadingRecords && (c && 'Loading...' === b.sLoadingRecords) && D(a, a, 'sZeroRecords', 'sLoadingRecords');
I will answer this question on my own thanks to developers of jQuery Datatables.
The problem was in the server side processing. When using diacritics the datatable is messing with the data so you have to actually control the diacritics with utf8_encode() php function

Datatables is not initializing columnFilter plugin

I already have a table
<table id="currencies-table" class="table table-striped table-bordered table-hover form-data-table">
<thead>
<tr>
<th style="width: 10px;"><input type="checkbox" class="group-checkable" data-set=".form-data-table .checkboxes" /></th>
<th><spring:message code="label.name_pl"/></th>
<th><spring:message code="label.name_en"/></th>
<th><spring:message code="label.name_de"/></th>
<th><spring:message code="label.code"/></th>
<th><spring:message code="label.symbol" /></th>
<th class="num-html-sort"><spring:message code="label.order" /></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach var="currency" items="${model.currencies}">
<tr class="odd gradeX">
<td><sf:checkbox path="ids" class="checkboxes" value="${currency.id}"/></td>
<td>${currency.name.pl}</td>
<td>${currency.name.en}</td>
<td>${currency.name.de}</td>
<td>${currency.code}</td>
<td>${currency.symbol}</td>
<td class="center">
<span class="move-arrow move-arrow-down" style="cursor:pointer"><i class="icon-arrow-down"></i></span>
<span class="priority-order badge badge-inverse">${currency.priority}</span>
<span class="move-arrow move-arrow-up" style="cursor:pointer"><i class="icon-arrow-up"></i></span>
</td>
<td><spring:message code="label.details"/></td>
</tr>
</c:forEach>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
This is the script that initializes this table.
var defaultSettings = function() {
return {
"bStateSave": true,
"bFilter": true,
"aLengthMenu": [
[5, 15, 20, -1],
[5, 15, 20, Labels.getLabel('label.all')] // change per page values here
],
"iDisplayLength": 15,
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sUrl": CommonsValues.datatable_lang_path()
},
"aoColumnDefs": [{
'bSortable': false,
'bSearchable': false,
'aTargets': [0, 'no-sort']
},
{
'bSortable': true,
'aTargets': ['date-sort'],
'sType': "date-pl"
},
{
'bSortable': true,
'aTargets': ['datetime-sort'],
'sType': "date-euro"
},
{
'sWidth': "100px",
'aTargets': ['size100']
},
{
'bSortable': true,
'aTargets': ['numeric-sort'],
'sType': "numeric"
},
{
'bSortable': true,
'aTargets': ['num-html-sort'],
'sType': 'num-html'
},
{
'bSortable': true,
'bSearchable': true,
'aTargets': ['rfq-sort'],
'sType': "rfq",
'mData': function(source, type, val) {
if (type === 'set') {
source.value = val;
source.value_display = val;
source.value_filter = val === "" ? "" : $.fn.dataTableExt.ofnSearch['rfq'](val);
return;
}
else if (type === 'display') {
return source.value_display;
}
else if (type === 'filter') {
return source.value_filter;
}
// 'sort', 'type' and undefined all just use the integer
return source.value;
}
},
{
'bSortable': true,
'aTargets': ['offer-sort'],
'sType': 'offer'
},
{
'bSortable': true,
'aTargets': ['price-sort'],
'sType': 'price'
}
],
"fnDrawCallback": function(oSettings) {
$('.group-checkable', oSettings.nTableWrapper).on('change', function() {
var checked = $(this).is(":checked");
$(oSettings.oInstance.fnGetNodes()).each(function() {
if (checked) {
$(this).find('.checkboxes').attr("checked", true);
} else {
$(this).find('.checkboxes').attr("checked", false);
}
$.uniform.update($(this).find('.checkboxes'));
});
}
);
}
};
};
var settings = new defaultSettings();
if ($(this).hasClass('expand-table')) {
settings.sScrollX = "125%";
}
var dataTable = $(this).dataTable(settings).columnFilter({
"sPlaceHolder": "head:after",
"aoColumns": [
null,
null,
{type: "checkbox"},
{type: "checkbox"},
{type: "checkbox"},
null,
null,
null
]
});
After initialization the table doesn't have the input for filtering columns even though other features works (sorting, main filtering, paging).
The table elements (thead,tbody,tfoot) are swapped in the resulting html code.
From what I can see from the provided example code I would say that you forgot to configure the values for the checkbox filters.
The followering should work:
var dataTable = $(this).dataTable(settings).columnFilter({
"sPlaceHolder": "head:after",
"aoColumns": [
null,
null,
{type: "checkbox", values: [ 'value used for filtering', 'displayed label text for checkbox']},
{type: "checkbox", values: ['bemol', 'user']},
{type: "checkbox", values: ['pl','Polish']},
null,
null,
null
]
});
Also try checking this example out:
Checkbox example

Categories

Resources