如何使用数据表实现 Daterangepicker?
Posted
技术标签:
【中文标题】如何使用数据表实现 Daterangepicker?【英文标题】:How to implement Daterangepicker with Datatables? 【发布时间】:2020-04-06 07:24:02 【问题描述】:我需要根据业务需求将此日期范围选择器与我的数据表一起使用。虽然,可以在这里看到我的日期范围排序和搜索的典型用法。 https://jsfiddle.net/zy914ko6/
我需要有关如何生成最小值和最大值以使实现适合绘制表格所需的 jQuery 脚本的帮助。 FMI:我在生产中使用服务器端 ajax 和 json。到目前为止,我的桌子正在运行,我确实获得了平局,但它没有反映“生效日期 [3]”列。
我的“有点”工作应用程序可以在这里查看http://live.datatables.net/pexopupu/1/edit]1
在这里可以看到我用于日期范围选择器的代码示例:
var table_1 = $('table.display#tb_posts').DataTable(
"processing": true,
"serverSide": true,
"ajax" :
"url" : " route('posts.list') ",
"type" : "GET"
,
"columns": [
data: 'check', name:'id', className: 'text-center' ,
data: 'DT_Row_Index', name:'DT_Row_Index', className: 'text-right' ,
data: 'id', name: 'posts.id', className: 'text-right' ,
data: 'title', name: 'posts.title',
data: 'username', name: 'users.username',
data: 'created_at', name: 'posts.created_at',
],
"autoWidth": true,
"order": [[ 3, 'asc' ]],
"sDom": "B<<'span8'f>r>t<<'col-sm-4'i><'col-sm-8'p>>",
"pagination": true,
"pagingType": "full_numbers"
);
//DateRangePicker
var startdate;
var enddate;
$('#reportrange').daterangepicker(
locale: format: 'DD/MM/YYYY' ,
ranges:
'All dates' : [moment().subtract(10, 'year'), moment().add(10, 'year')],
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'7 last days': [moment().subtract(6, 'days'), moment()],
'30 last days': [moment().subtract(29, 'days'), moment()],
'This month': [moment().startOf('month'), moment().endOf('month')],
'Last month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
,
"opens": "left",
"applyClass": "btn-primary",
"showDropdowns": true,
,
function (start, end, label)
var s = moment(start.toISOString());
var e = moment(end.toISOString());
startdate = s.format("YYYY-MM-DD");
enddate = e.format("YYYY-MM-DD");
);
//Filter the datatable on the datepicker apply event
$('#reportrange').on('apply.daterangepicker', function (ev, picker)
startdate = picker.startDate.format('YYYY-MM-DD');
enddate = picker.endDate.format('YYYY-MM-DD');
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex)
if (startdate != undefined)
var coldate = aData[3].split("/");
var d = new Date(coldate[2], coldate[1] - 1, coldate[1]);
var date = moment(d.toISOString());
date = date.format("YYYY-MM-DD");
dateMin = startdate.replace(/-/g, "");
dateMax = enddate.replace(/-/g, "");
date = date.replace(/-/g, "");
if (dateMin == "" && date <= dateMax)
return true;
else if (dateMin == "" && date <= dateMax)
return true;
else if (dateMin <= date && "" == dateMax)
return true;
else if (dateMin <= date && date <= dateMax)
return true;
return false;
);
table_1.draw()
);
你能帮我找到解决办法吗... 我不确定我哪里出错了。
【问题讨论】:
经过进一步调查,它以某种方式以 dd-mm-yyyy 格式实现,因此它认为“生效日期[3]”列中的信息采用上述格式。在我的日历中执行 'from date of' 01/01/2019 和 'to date of' 01/04/2019 当它需要以 mm-dd-yyyy 格式读取时正确排序......在我的代码中@ live.datatables.net/pexopupu/1/edit 您可以看到所有内容都设置为 mm-dd-yyyy 但仍然以某种方式实现为 dd-mm-yyyy ..... 我认为这可能会对您有所帮助:daterangepicker.com 您可以选择您选择的日期范围选择器,并像在此处所做的那样在您的应用程序中使用它。 我正在使用它......主观是在数据表实现的最佳实践中编码 【参考方案1】:Via assistance received from Datatables.net forum.
var startdate;
var enddate;
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex)
if (typeof startdate === 'undefined' || typeof enddate === 'undefined')
return true;
var coldate = moment(aData[3], 'DD-MM-YYYY');
console.log('coldate', coldate)
var valid = true;
if (coldate.isValid())
if (enddate.isBefore(coldate))
console.log('enddate before coldate', enddate)
valid = false;
if (coldate.isBefore(startdate))
console.log('coldate before startdate', startdate)
valid = false;
else
valid = false;
return valid;
);
jQuery(document).ready(function ($)
var table;
$.ajax(
url: "table.json",
dataType: "jsonp", // jsonp
type: "POST",
jsonpCallback: 'processFunction', // add this property
contentType: "application/json; charset=utf-8",
success: function (result, status, xhr)
table = $('#poview').DataTable(
initComplete: function ()
this.api().columns([1]).every( function ()
var column = this;
var select = $('<select class="custom-select custom-select-sm rowSort"><option value="">Trans Type</option></select>')
.appendTo( $('#rowSort' ))
.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>' );
);
);
$('#poview_info').appendTo($('#sumInfo'));
$('#poview_paginate').appendTo($('#pageInfo'));
,
"pagingType": "first_last_numbers",
"scrollX": true,
fixedHeader: true,
fixedColumns:
leftColumns: 2
,
"bAutoWidth": true,
sDom: 't<i><""p>',
data: result,
columns: [
data: 'policy number' ,
data: 'transaction type' ,
data: 'transaction date' ,
data: 'transaction effective date' ,
data: 'minimum premium amount' ,
data: 'deferred premium amount' ,
data: 'total written premium' ,
data: null,
className: "center actionItem",
defaultContent: '<button class="btn actionIcon" data- toggle="modal" data-target="#modal-1"><i class="fas fa-calculator"></i></button>'
],
columnDefs: [
targets: -1,
className: 'dt-nowrap',
className: 'dt-left'
],
"pageLength": 5
);
$('#reportrange').daterangepicker(
locale: "format": "MM/DD/YYYY",
"separator": " - ",
"applyLabel": "Apply",
"cancelLabel": "Cancel",
"fromLabel": "From",
"toLabel": "To",
"firstDay": 1,
"opens": "right",
"startDate":startdate,
,
function (start, end, label)
console.log('New date range selected: ' + start.format('YYYY-MM-DD')
+ ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
);
,
error: function (xhr, status, error)
console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText);
);
$('#reportrange').on('apply.daterangepicker', function (ev, picker)
startdate = moment(picker.startDate.format('DD-MM-YYYY'), 'DD-MM-YYYY');
enddate = moment(picker.endDate.format('DD-MM-YYYY'), 'DD-MM-YYYY');
table.draw();
);
);
【讨论】:
以上是关于如何使用数据表实现 Daterangepicker?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用bootstrap的daterangepicker插件
如何本地化 jQuery UI DateRangePicker?
如何使用bootstrap的daterangepicker插件