pagination doesn't appear datatable - javascript

There is a data table with export to PDF or Excel and print buttons.But pagination doesn't appear. When I have looked examples most of them same as my project; when they put button, pagination doesn't appear. How can I solve the problem?
js code of Data table is below;
var oTable = $('#datatables').dataTable({
destroy: true,
"bSort": false,
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
footer: true ,
exportOptions: {
columns: [0, 1, 2, 3, 4,5,6,7]
}
},
{
extend: 'pdfHtml5',
exportOptions: {
columns: [0, 1, 2, 3, 4, 5]
},
customize: function (doc) {
//Remove the title created by datatTables
doc.content.splice(0, 1);
//Create a date string that we use in the footer. Format is dd-mm-yyyy
var now = new Date();
var jsDate = now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear();
// doc.pageMargins = [20, 60, 20, 30];
// Set the font size fot the entire document
doc.defaultStyle.fontSize = 9;
// Set the fontsize for the table header
doc.styles.tableHeader.fontSize = 9;
// Create a header object with 3 columns
// Left side: Logo
// Middle: brandname
// Right side: A document title
doc['header'] = (function () {
return {
columns: [
{
alignment: 'left',
italics: true,
text: 'dataTables',
fontSize: 18,
margin: [10, 0]
},
{
alignment: 'right',
fontSize: 14,
text: $("#drpIller option:selected").text() + " " + $("#drpIlceler option:selected").text()
}
],
margin: 20
}
});
doc['footer'] = (function (page, pages) {
return {
columns: [
{
alignment: 'left',
text: ['Oluşturulma tarihi: ', { text: jsDate.toString() }]
},
{
alignment: 'right',
text: ['page ', { text: page.toString() }, ' / ', { text: pages.toString() }]
}
],
margin: 20
}
});
var objLayout = {};
objLayout['hLineWidth'] = function (i) { return .5; };
objLayout['vLineWidth'] = function (i) { return .5; };
objLayout['hLineColor'] = function (i) { return '#aaa'; };
objLayout['vLineColor'] = function (i) { return '#aaa'; };
objLayout['paddingLeft'] = function (i) { return 4; };
objLayout['paddingRight'] = function (i) { return 4; };
doc.content[0].layout = objLayout;
}
},
{
extend: 'print'
}
],
"responsive": true,
"data": data,
"columns": [
{ "data": "A", "autoWidth": true},
{ "data": "S", "autoWidth": true},
{ "data": "D", "autoWidth": true },
{ "data": "E", "autoWidth": true},
{ "data": "F", "autoWidth": true },
{ "data": "G", "autoWidth": true }
],
"bAutoWidth": false
}
});
thanks your valuable for helps.

I found answer at this link:
https://codepen.io/RedJokingInn/pen/XMVoXL
It is abouth dom options.
It is solved When I write
"dom": '<"dt-buttons"Bf><"clear">lirtp'
instead
dom: 'Bfrtip'
tutorial at the link also consists printing page numbers and printing same sentence top of every pages informations.
May be can help someone in the future.

Related

Datatables - Export values inside and outside the field input and value of the select field

let's see who can help me solve this problem.
I have several tables with the JS datatables plugin (https://datatables.net/)
My problem is in exporting the data in PDF and Excel.
I can not export to PDF or Excel the values that are inside the input or select fields (only the selected value)
I have several tables where there are columns that are inputs, another column selects and another column simple text. I would like to know how I can do to export all these values to Excel or PDF, if you can with this plugin. So far I have not been able to get it.
Here a extract of my code to build the datatable:
var tabla_table = $('#table').DataTable({
dom: 'Blfrtip',
buttons: [{
extend: 'collection',
text: "<i class='fa fa-cog'></i>",
buttons: [
{
extend: 'pdfHtml5',
orientation: 'landscape',
customize: function ( doc ) {
doc.defaultStyle.fontSize = 10;
},
exportOptions: {
columns: ':visible',
columns: ':not(.no-print)',
/* format: {
body: function ( data, row, column, node, sValue, nTr, type ) {
//
//check if type is input using jquery
// console.log('data val: ' + $(data).val() );
console.log('data: ' + data );
console.log('row: ' + row );
console.log('nTr: ' + nTr );
console.log('node: ' + node );
console.log('type: ' + type );
/*if( $(data).is("input") ){
return data;
}else{
return $(data).val();
}
}
}*/
//columns: [4, 8, 9, 10, 11, 12, 13, 14]
}
},{
extend: 'excel',
orientation: 'landscape',
exportOptions: {
columns: ':visible',
columns: ':not(.no-print)',
format: {
body: function ( data, row, column, node ) {
//
//check if type is input using jquery
//console.log('PRUEBA: ' + $(data).val() );
if( $(data).is("input") ){
return data;
}else{
return $(data).val();
}
}
}
//columns: [4, 8, 9, 10, 11, 12, 13, 14]
}
},{
text: 'Imprimir',
extend: 'print',
orientation: 'landscape',
exportOptions: {
columns: ':visible',
columns: ':not(.no-print)'
}
},
/* 'colvis'*/
]
}
],.....
Out put in PDF:
I hope I could have provided enough information to resolve this, if it can be resolved. And if more information is needed, do not hesitate to tell me.
Thank you very much in advance
I've been struggling with this one recently and finally found the solution. I'll try to make it a bit more detailed.
Here's a function that checks if the exported node is the node. In such case it returns the input.value - otherwise just the data:
//function for DataTable data export to export <input>.value
var buttonCommon = {
exportOptions: {
format: {
body: function ( data, row, column, node ) {
//check if type is input using jquery
return node.firstChild.tagName === "INPUT" ?
node.firstElementChild.value :
data;
}
}
}
};
Now, with this function defined, we use it to extend the buttons:
buttons: [
$.extend( true, {}, buttonCommon, {
extend: 'copyHtml5'
} ),
$.extend( true, {}, buttonCommon, {
extend: 'excelHtml5'
} ),
$.extend( true, {}, buttonCommon, {
extend: 'pdfHtml5'
} ),
$.extend( true, {}, buttonCommon, {
extend: 'csvHtml5'
} )
],
var buttonCommon = {
exportOptions: {
format: {
body: function(data, column, row, node) {
if (row == 1) {
return $(data).is("div") ? $(data).text() : data
}
else if (row == 4) {
return $(data).is("select") ? $(data).val() : data
}
else {
return $(data).is("input") ? $(data).val() : data
}
}
}
}
};
$(document).ready(function() {
$('#tables').DataTable({
dom: 'Bfrtip',
"paging": !1,
buttons: [$.extend(!0, {}, buttonCommon, {
extend: "excel"
})]
})
});
ok, in your button
exportOptions: {
orthogonal: 'export',
}
in your columns :
render: function (data, type, row) {
return type === 'export' ? row.Descripcion: "";
}

Limit checked , checkbox in bootstrap dataTable

I have this code below to click a checkbox in my DataTable and get the IDs and store in an array. For Example I have a 2 seperate DataTables First is for President and second is for the Senators.
We know that we can only vote 1 in President and for Senators we can choose many.
My problem here is I can check how many checkboxes in the DataTables. How to limit the checked checkboxes?.
Still learning in bootstrap here.
JS Code
var dataTablestest = $("#tbltest").DataTable({
responsive: true,
processing: true,
info: true,
search: true,
stateSave: true,
order: [[1, "asc"], [2, "asc"]],
lengthMenu: [[50, 100, 200, -1], [50, 100, 200, "All"]],
ajax: { "url": "/Voting/LoadTableTest" },
columns:
[
{ data: "testID", title: "", visible: false, searchable: false },
{ data: "Fullname", title: "FullName", sClass: "alignRight" },
{ data: "Position", title: "Position", sClass: "alignRight" },
{ data: "party", title: "Party", sClass: "alignRight" },
{ data: "ActionMenu", title: "Click to vote", searchable: false, orderable: false, sClass: "alignCenter",
"mRender": function (data) {
return '<center><label><input class="checkId" type="checkbox" id="chkvote_' + data + '" value=""/></label></center>';
}
}
]
});
var arrayIds = [];
$('#tbltest tbody').on('click', 'tr', function (e) {
if ($(e.target).is(".checkId")) {
var Ids = dataTablestest.row(this).data().testID;
arrayIds.push(Ids);
return
}
});
EDIT
I found an answer but there is a problem with it. My counter keeps increment every time I check a checkbox from my dataTable.
$('#tbltest tbody').on('click', 'tr', function (e) {
if ($(e.target).is(".checkId")) {
if ($(e.target).is(":checked") == true) {
CheckCount = CheckCount + 1;
var Ids = dataTablestest.row(this).data().testID;
if (CheckCount > 1) {
return false;
}
arrayIds.push(Ids);
return
}
else {
CheckCount = parseInt(CheckCount) - parseInt(1);
}
}
});
I use this code below.. Thanks to all who view my thread.
var arrayIds = [];
$('#tbltest tbody').on('click', 'tr', function (e) {
if ($(e.target).is(".checkId")) {
var Ids = dataTablestest.row(this).data().testID;
if ($(e.target).is(":checked") == true) {
var lenArray = arrayIds.length;
if (lenArray < 1) {
arrayIds.push(Ids);
} else {
return false;
}
}
else {
for (var i = arrayIds.length - 1; i >= 0; i--) {
if (arrayIds[i] === Ids) {
arrayIds.splice(i, 1);
}
}
}
}
return;
});

How to increment javascript variable on click of Excel Button in datatables bootstrap

var counter = 0;
function staticVar()
{
if (staticVar.counter == undefined)
{
staticVar.counter = 1
}
else
{
staticVar.counter++
}
return staticVar.counter;
}
//Our table has horizontal and vertical scroll bars and the first columni.e, the serial number will be fixed when scrolling
$(document).ready(function() {
var download_file_counter= staticVar();
var table = $('#example').DataTable({
"aoColumnDefs": [{ "bSortable": false, "aTargets": [0] }],
scrollY: '40vh',
scrollX: '40vh',
paging: true,
pageLength: 20,
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
dom: 'Bflrtip',
buttons: [{
extend: 'print',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'colvis',
className: 'colvisButton'
},
{
extend: 'excelHtml5',
title: 'LicenseDetails_'+(++download_file_counter)+'_'+today,
text: 'Excel',
exportOptions: {
modifier: {
page: 'current'
}
}
}],
columnDefs: [{
targets: -1,
visible: false,
orderable: false
}],
order: [[ 1, 'asc' ]]
});
download_file_counter= makeCounter();
$('#start-date, #end-date').change(function () {
table.draw();
});
$('#start-date1, #end-date1').change(function () {
table.draw();
});
$('#start-date2, #end-date2').change(function () {
table.draw();
});
});
This is my javascript code I want to pass the counter variable to the filename on clicking of the excel button. The counter is not incrementing for onclick of that.

ui-grid enableSelectAll and paginationPageSize

I have a grid and I would like giving a pagination size of 10, I want to select all options to restrict row selection to only 10, but given this configuration, it selects entire data set across all pages.
$scope.gridEvents = {
enableSorting : true,
enableSelectAll: true,
enableColumnResize: true,
enablePaginationControls: false,
rowHeight: 27,
enableScrollbars : true,
paginationPageSize : 10
}
any help is appreciated
Please try as shown below.
Working Plunker
JS
$scope.gridOptions = {
paginationPageSizes: [10, 20, 30],
paginationPageSize: 10,
useExternalPagination: true,
enableRowSelection: true,
enableSelectAll: true,
totalItems: 100,
columnDefs: [
{ name: 'name' },
{ name: 'gender' },
{ name: 'company' }
],
onRegisterApi: function(gridApi){
$scope.gridApi = gridApi;
$scope.gridApi.pagination.on.paginationChanged( $scope, function( currentPage, pageSize){
$scope.getPage(currentPage, pageSize);
});
}
};
$scope.getPage = function(pageNumber, pageSize){
var startingRow = pageSize * ( pageNumber - 1); // page number starts at 1, not zero
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
.success(function (data) {
var newData = [];
for( var i = startingRow; i < startingRow + $scope.gridOptions.paginationPageSize; i++ ) {
newData.push( data[i] );
}
$scope.gridOptions.data = newData;
});
};
$scope.getPage(1, 10);
Html
<div ui-grid="gridOptions" ui-grid-pagination ui-grid-selection class="grid"></div>

jqGrid FilterToolbar with mostly working daterange picker

I am using the free jqGrid v4.12.1. (Can't post links to fiddle yet so code follows post)
The primary issue is that we are trying to do all searching/filtering with the filterToolbar. Oleg had helped a few weeks back push just dates to the search modal, but the requirement has changed to get a date range picker working in the filterToolbar. We are mostly there. Using Dan Grossman's bootstrap daterange picker and calling a custom function, it works like a charm.
Entering DateRangeFirst
The problem originally came in to play when you would select another value like an invoice amount. It would then override the date range and give all values "ge" to the start date. So it was seeing the beginning date of the string. To circumvent this, I called the invoiceDateSearch function again in beforeSearch. This way it ran the function again and recognized the start date and end dates along with the new value we are asking for.
The thing that happens now is that if I put any other value in first and then select a daterange, the daterange won't fire until I key some other search criteria and back it out.
AnyOther value first
It doesn't even recognize the date range was entered yet, when clearly it is there. triggerToolbar, reload grid is called in the function for the invoice date search.
When using beforeSearch, keeps the date range as a date range and not a string...regardless of how often the toolbar is triggered and values are backed out of any other fields, which is great. The downside to it is if a user puts a value other than the date range FIRST, the date range doesn't work...unless a subsequent field is entered. Not using it, converts the date range to a string after the first time it is used and any other values entered or filtered will require re-running the date parameters, because it gives every date greater than the start date.
I've put advanced search on the grid while troubleshooting. I'd like to take it off (or at least the buttons), as users want to just use the toolbarFilter.
My questions, how can I get the date range picker working in concert with the other column values? Is there an issue running two date pickers at once? The single date date picker just isn't responding at all when it's used. It will put the date there, and once another field is fired, it will respond, but never by itself.
Sorry if I "info dumped" I am fairly new at this. I've searched quite a bit for help to this and can't find much of anything. If I keep hacking at this, I am going to tear up what I have working! :O
Thanks in advance for any help or guidance!
$(function () {
"use strict";
var $grid = $("#vGrid2"),
lastSel;
function modifySearchingFilter(separator) {
var i,
l,
rules,
rule,
parts,
j,
group,
str,
filters = $.parseJSON(this.p.postData.filters);
if (filters && typeof filters.rules !== 'undefined' && filters.rules.length > 0) {
rules = filters.rules;
for (i = 0; i < rules.length; i++) {
rule = rules[i];
if (rule.op === 'cn') {
// make modifications only for the 'contains' operation
parts = rule.data.split(separator);
if (parts.length > 1) {
if (typeof filters.groups === 'undefined') {
filters.groups = [];
}
group = {
groupOp: 'AND',
groups: [],
rules: []
};
filters.groups.push(group);
for (j = 0, l = parts.length; j < l; j++) {
str = parts[j];
if (str) {
// skip empty '', which exist in case of two separators of once
group.rules.push({
data: parts[j],
op: rule.op,
field: rule.field
});
}
}
rules.splice(i, 1);
i--; // to skip i++
}
}
}
this.p.postData.filters = JSON.stringify(filters);
}
};
//TODO: search is filtering in the grid but only from start date and either ge or le start date based on which is first in the column
//TODO: (cont)model. Need to see why end date is not picking up from function.
function invoiceDateSearch($subGrid) {
var postData = $subGrid.getGridParam("postData");
// If there is no post data for some reason, get outta here
if (!postData) {
return;
}
// Make sure the filters object is constructed
var field = "InvoiceDate";
if (!postData.filters) {
postData.filters = {
groupOp: "AND",
rules: []
}
} else {
postData.filters = jQuery.jgrid.parse(postData.filters);
// Need to clear out existing invoice date rules
for (var i = postData.filters.rules.length - 1; i >= 0; i--) {
if (postData.filters.rules[i].field === field) {
postData.filters.rules.splice(i, 1);
}
}
}
var dateRangeString = $("#gs_InvoiceDate").val();
if (dateRangeString.length > 0) {
var dateRange = dateRangeString.split("-");
var startDate = dateRange[0];
var endDate;
if (dateRange.length == 1) {
endDate = dateRange[0];
} else {
endDate = dateRange[1];
}
postData.filters.rules.push({ "field": field, "op": "ge", "data": startDate.trim() });
postData.filters.rules.push({ "field": field, "op": "le", "data": endDate.trim() });
postData.filters = JSON.stringify(postData.filters);
// Need to set the grid's search to true, not the postData's
$subGrid.setGridParam({ search: true });
$subGrid.trigger("reloadGrid", [{ current: true, page: 1 }]);
}
}
function paymentDateSearch($subGrid) {
var postData = $subGrid.getGridParam("postData");
// If there is no post data for some reason, get outta here
if (!postData) {
return;
}
// Make sure the filters object is constructed
var field = "PaymentDate";
if (!postData.filters) {
postData.filters = {
rules: []
}
} else {
postData.filters = jQuery.jgrid.parse(postData.filters);
// Need to clear out existing invoice date rules
for (var i = postData.filters.rules.length - 1; i >= 0; i--) {
if (postData.filters.rules[i].field === field) {
postData.filters.rules.splice(i, 1);
}
}
}
var dateString = $("#gs_PaymentDate").val();
if (dateString.length > 0) {
var startDate = dateRange[0];
postData.filters.rules.push({ "field": field, "op": "eq", "data": startDate.trim() });
postData.filters = JSON.stringify(postData.filters);
// Need to set the grid's search to true, not the postData's
$subGrid.setGridParam({ search: true });
$subGrid.trigger("reloadGrid", [{ current: true, page: 1 }]);
}
}
//**TO overwrite jquery.ui icons and use fontAwesome. extending allows for customization of fA icons set as default in grid**//
$.extend(true, $.jgrid.icons.fontAwesome, {
common: "fa",
sort: {
common: "fa-sort fa-lg"
//asc: "fa-sort",
//desc: "fa-sort"
},
nav: {
common: "fa",
refresh: "fa-recycle fa-lg"
}
});
//**TOOLTIP ADD ON**//
$("[title]").qtip({
position: {
my: "bottom center",
at: "top center",
viewport: $(window)
}
});
//**PRIMARY GRID**//
$grid.jqGrid({
url: "VendInvoice/Vendor",
datatype: "local",
data: gridData,
colNames: ["ID", "Vendor Number", "Vendor Name", "dba", "VendorDbaCombo"],
colModel: [
{ key: true, name: "ID", width: 0, hidden: true, sortable: false, search: false },
{
key: false,
title: false,
name: "VendorNo",
index: "VendorNo",
width: 100,
sortable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["cn"],
attr: { title: "Enter all or part of a Vendor Number." },
clearSearch: false
}
},
{
key: false,
title: false,
name: "VendorName",
//index: "VendorName",
width: 500,
sortable: true,
search: true,
clearSearch: false,
stype: "text",
searchoptions: {
sopt: ["cn"],
clearSearch: false, //removes X in column filters
attr: {
title: "Enter a Vendor Name. SEARCHTIP: Once you start typing, you will begin returning filtered data. To broaden results returned provide less information, to narrow results provide more.",
maxlength: 9080,
dataInit: function (elem) {
$(elem).width(600);
}
}
}
},
{
key: false,
title: false,
name: "Dba",
index: "Dba",
width: 500,
sortable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["cn"],
attr: { title: "Enter all or part of a dba." },
clearSearch: false
}
},
{ key: false, name: "VendorDbaCombo", index: "VendorDbaCombo", width: 1, hidden: true }
],
//**PRIMARY GRID PROPERTIES**//
cmTemplate: { autoResizable: true, editable: true },
iconSet: "fontAwesome",
hidegrid: false,
forceFit: true,
caption: "Vendor Results",
ignoreCase: true,
gridview: true,
autoencode: true,
pager: "#Pager",
toppager: true,
rowNum: 25,
rowList: [5, 10, 25],
autowidth: true,
height: "auto",
viewrecords: true,
loadonce: true,
sortName: "VendorName",
sortOrder: "ASC",
viewsortcols: [true, "vertical", true],
forceClientSorting: true,
multiselect: true,
setGridWidth: 980,
loadtext: "Fetching your data, back in a jiff!",
emptyrecords: "There were no records, try narrowing your search criteria",
loadComplete: function () {
$(this).find(">tbody>tr.jqgrow:visible:odd").addClass("myAltRowClass");
},
onSelectRow: function (row_id) {
$grid.jqGrid("toggleSubGridRow", row_id);
if (row_id !== lastSel && typeof lastSel !== "undefined") {
$grid.jqGrid("setRowData", row_id, false, "myNormal");
}
$grid.jqGrid("setRowData", row_id, false, "myBold");
lastSel = row_id;
},
//**SET SUBGRID**//
subGrid: true,
subGridOptions: {
plusicon: "fa fa-plus-square-o",
minusicon: "fa fa-minus-square-o",
reloadOnExpand: false,
expandOnLoad: false,
delayOnLoad: 50
},
jsonReader: {
id: "id",
root: "rows",
total: "total",
records: "records",
subgrid: {
root: "rows",
repeatitems: true, //must be true in subgrid and false in main grid
cell: ""
}
},
subGridRowExpanded: function (subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + "_t";
var selectedrow = $(this).jqGrid('getRowData', row_id);
pager_id = "p_" + subgrid_table_id;
var stat = function (subgrid_id, row_id) {
$("#vGrid2").jqGrid("setSelection", "row_id"); //Test to set selection for toggle
}
//**SUBGRID**//
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "'class='scroll'></table><div id='" + pager_id + "'class='scroll'></div>");
$("#" + subgrid_table_id).jqGrid({
url: "VendInvoice/VendInvoiceSubGridData?vendorID=" + row_id,
datatype: "local",
data: subgridData[rowId],
postData: {
vendorID: row_id,
},
colNames: ["vendorID", "Invoice Status", "Invoice No", "Invoice Date", "Invoice Amount($)", "Payment Date", "Check or ACH Number", "Check or ACH Amount($)", "Encashment Date"],
colModel: [
{ name: "vendorID", key: true, index: "vendorID", hidden: true, width: 0 },
{
name: "InvoiceStatus",
title: false,
index: "InvoiceStatus",
width: 140,
sortable: true,
search: true,
formatter: "select",
stype: "select",
searchoptions: {
sopt: ["cn"],
attr: { title: "If part of your search criteria, select an invoice status from the drop-down menu." },
value: ":Select (All);Paid:Paid;Processing for Payment:Processing for Payment;Reviewing:Reviewing"
}
},
{
name: "InvoiceNo",
title: false,
index: "InvoiceNo",
width: 125,
sortable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["cn", "eq"],
attr: { title: "Enter all or part of an invoice number." },
clearSearch: false
}
},
{
name: "InvoiceDate",
title: false,
index: "InvoiceDate",
width: 135,
formatter: "date",
formatoptions: { srcformat: "m/d/Y", newformat: "m/d/Y" },
jsonmap: function (obj) {
var d = new Date(parseInt(obj.matchstartDate, 10));
return d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
},
sortable: true,
sorttype: "date",
editable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["ge", "le"],
clearSearch: false,
attr: { title: "Click in the box to open the date range picker." },
dataInit: function (elem) {
$(elem).daterangepicker({
dateFormat: 'mm/dd/yy',
changeYear: true,
changeMonth: true,
todayHighlight: true,
});
//ranges: {
// "Yesterday": [moment(), subtract(1, 'days'), moment().subtract(1, 'days')],
// "Last 7 days": [moment().subtract(6, 'days'), moment()],
// "Last Month": [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
// "This YTD": [moment().startOf('year'), moment().endOf('year')],
// "LastYear": [moment().subtract(1,'year').startOf('year'), moment.subtract(1,'year').endOf('year')]
// }
$(document).on('apply.daterangepicker', function () {
var $subGrid = $("#" + subgrid_table_id);
invoiceDateSearch($subGrid);
});
}
}
},
{
name: "InvoiceAmount",
title: false,
index: "InvoiceAmount",
width: 95,
sortable: true,
sorttype: "float",
formatter: "currency",
formatoptions: {
//prefix: "$",
suffix: "", thousandsSeparator: ",", decimalPlaces: 2
},
search: true,
stype: "text",
searchoptions: {
sopt: ["eq"],
attr: { title: "Enter an invoice amount." },
clearSearch: false
}
},
{
name: "PaymentDate",
title: false,
index: "PaymentDate",
width: 135,
formatter: "date",
formatoptions: { srcformat: "m/d/Y", newformat: "m/d/Y" },
jsonmap: function (obj) {
var d = new Date(parseInt(obj.matchstartDate, 10));
return d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
},
sortable: true,
sorttype: "date",
editable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["eq"],
clearSearch: false,
attr: { title: "Click in the box to open the date range picker." },
dataInit:
function (el) {
$(el).datepicker({
dateFormat: 'mm/dd/yy',
changeYear: true,
changeMonth: true,
todayHighlight: true,
orientation: "bottom",
immediateUpdates: true,
autoclose: true
}).on('changeDate', function () {
var $subGrid = $("#" + subgrid_table_id);
paymentDateSearch($subGrid);
$subGrid.setGridParam({ search: true });
$subGrid.trigger("reloadGrid", [{ current: true, page: 1 }]);
});
}
}
},
{
name: "PaymentNo",
title: false,
index: "PaymentNo",
width: 115,
sortable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["cn", "eq"],
attr: { title: "Enter all or part of a Check or ACH Number." },
clearSearch: false
}
},
{
name: "CheckAmount",
title: false,
index: "CheckAmount",
width: 95,
sortable: true,
sorttype: "float",
formatter: "currency",
formatoptions: { suffix: "", thousandsSeparator: ",", decimalPlaces: 2 },
search: true,
stype: "text",
searchoptions: {
sopt: ["eq"],
attr: { title: "Enter a payment amount." },
clearSearch: false
}
},
{
name: "EncashmentDate",
title: false,
index: "EncashmentDate",
width: 100,
sortable: true,
sorttype: "date",
formatter: "date",
formatoptions: { srcformat: "m/d/Y", newformat: "m/d/Y" },
search: false
}
],
//**SUBGRID PROPERTIES**//
cmTemplate: {
align: "center",
autoResizeable: true
},
idPrefix: "_s",
iconSet: "fontAwesome",
loadonce: true,
loadtext: "Grabbing those invoice, this may take a second!",
autoencode: true,
toppager: true,
autowidth: true,
sortable: true,
showOneSortIcon: true,
autoResizing: { widthOfVisiblePartOfSortIcon: 13 },
viewsortcols: [true, "vertical", true],
multiselect: true,
height: "auto",
rowNum: 500,
rowList: [25, 50, 100, 250, 500],
gridview: true,
viewrecords: true,
emptyrecords: "There were no records, try narrowing your search criteria",
prmNames: {
id: "vendorID"
},
pager: "#" + pager_id,
loadComplete: function () {
$(this).find(">tbody>tr.jqgrow:visible:odd").addClass("myAltRowClass2");
},
beforeSelectRow: function () {
return false;
}
});
jQuery("#" + subgrid_table_id).jqGrid("navGrid", "#" + pager_id, {
edit: false,
add: false,
del: false,
search: true,
refresh: true,
refreshtext: "Refresh Invoice Results",
cloneToTop: true
},
{},
{},
{},
{
multipleSearch: true,
});
jQuery("#" + subgrid_table_id).jqGrid("navButtonAdd", "#" + pager_id, {
caption: "Export to Excel",
buttonicon: "fa-file-excel-o",
onClickButton: function (e) {
exportData(e, "#" + subgrid_table_id);
},
position: "last"
});
jQuery("#" + subgrid_table_id).jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: false,
ignoreCase: true,
autoSearch: true,
autosearchDelay: 1000,
attr: {
style: "width: auto;padding:0;max-width:100%"
},
defaultSearch: "cn",
//beforeSearch: function () {
// var $subGrid = $("#" + subgrid_table_id);
// invoiceDateSearch($subGrid);
// $subGrid.trigger("reloadGrid", [{ current: true, page: 1 }]);
//}
});
$("[title]").qtip({
position: {
my: "bottom center",
at: "top center",
viewport: $(window)
}
});
var names = [
"Invoice Status", "Invoice No", "Invoice Date", "Invoice Amount", "Payment Date",
"Check or ACH No", "Check or ACH Amount", "Encashment Date"
];
var mydata = [];
var i, j;
if (mydata != null) {
for (i = 0; i < mydata.length; i++) {
mydata[i] = {};
for (j = 0; j < mydata[i].length; j++) {
mydata[i][names[j]] = mydata[i][j];
}
}
}
for (var i = 0; i <= mydata.length; i++);
$("#" + subgrid_table_id).jqGrid('addRowData', i + 1, mydata[i]);
}
}).jqGrid("navGrid", "#Pager", {
edit: false,
add: false,
del: false,
search: false,
refresh: true,
refreshtext: "Refresh Results",
cloneToTop: true
}).jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: false,
ignoreCase: true,
autoSearch: true,
autosearchDelay: 1000,
attr: {
style: "width: auto;padding:0;max-width:100%"
},
defaultSearch: "cn",
beforeSearch: function () {
modifySearchingFilter.call(this, " ");
}
}).jqGrid("gridResize");
//**TOOLTIP ADD ON**//
$("[title]").qtip({
position: {
my: "bottom center",
at: "top center",
viewport: $(window)
}
});
//**HIDE 'SELECT ALL' CHECKBOX** call after grid is loaded//
$("#cb_" + $grid[0].id).hide();
$("#vGrid2").jqGrid("hideCol", "subgrid");
//**CUSTOM TOOLTIP TEXT FOR COLUMN HEADERS IN PRIMARY GRID**//
var setTooltipsGrid = function (grid, iColumn, text) {
var thd = jQuery("thead:first", grid[0].grid.hDiv)[0];
jQuery("tr.ui-jqgrid-labels th:eq(" + iColumn + ")", thd).attr("title", text);
};
$(".hasTooltip").each(function () {
$(this).qtip({
content: {
text: $(this).next("div")
}
});
});
//setTooltipsGrid($("#vGrid2"), 0, "If exporting, ensure ONLY the row you wish to export is selected. Remove any unnecessary checks in this column.");
//**EXPORT TO EXCEL-CSV**//
function exportData(e, row_id) {
var subGrid = jQuery(row_id).getDataIDs(); // Get all the ids in array
var label = jQuery(row_id).getRowData(subGrid[0]); // Get First row to get the labels
var selRowIds = jQuery(row_id).jqGrid('getGridParam', 'selarrrow');
var obj = new Object();
obj.count = selRowIds.length;
if (obj.count) {
obj.items = new Array();
var elem;
for (elem in selRowIds) {
if (selRowIds.hasOwnProperty(elem)) {
obj.items.push(jQuery(row_id).getRowData(selRowIds[elem]));
}
}
var json = JSON.stringify(obj);
JSONToCSVConvertor(json, "csv", 1);
}
}
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData.items[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.items.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData.items[i]) {
row += '"' + arrData.items[i][index].replace(/(<([^>]+)>)/ig, '') + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//*** FORCE DOWNLOAD ***//
//will generate a temp "a" tag
var link = document.createElement("a");
link.id = "lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
var blob = new Blob([csv], { type: 'text/csv' });
var myURL = window.URL || window.webkitURL;
var csvUrl = myURL.createObjectURL(blob);
var filename = 'UserExport.csv';
jQuery("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
});
It seems to me that the usage of custom operation is the best approach to solve your problem. Of cause you can use beforeSearch callback of filterToolbar to modify the filter, but it's too low level operation and it will not work in Searching Dialog.
I would recommend you to read the wiki article which describes the feature. It provides an example with "numeric IN" operation, which you can easy modify to your requirements. The filter callback get in options all the information which you need and the callback should just verify that the data of the testing item (options.item) are inside of interval provided by the value from the date range picker (options.searchValue). I think that you will get small code, which solves your problem, in the way.
Final remark: I'd recommend you to upgrade to the latest 4.13.0 version which fix some bugs, improves performance in some cases and provides new features described in the readme.

Categories

Resources