Home Web Front-end JS Tutorial Detailed explanation of the use of daterangepicker control

Detailed explanation of the use of daterangepicker control

Apr 17, 2018 am 09:12 AM
control Detailed explanation


This time I will bring you a detailed explanation of the use of the daterangepicker control. What are the precautions when using the daterangepicker control? The following is a practical case, let’s take a look. one time.

Dual calendar time period selection plug-in - daterangepicker is a time control in the later stage of bootstrap framework. It can set multiple time period options or customize the time period, and the user can choose it. The start time and end time, and the maximum span of the time period can be set in the program.

1. Quote

daterangepicker relies on monent.js and jquery. Therefore, monent.js, jquery, and bootstrap must be introduced before daterangepicker is introduced during use.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="moment.js"></script>
<script type="text/javascript" src="daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.css" />
<link rel="stylesheet" type="text/css" href="daterangepicker-bs3.css" />
Copy after login

Or when using Modular programming, such as when using seaj.js, add

in front of the entire code compression define("gallery/daterangepicker/1.3.7/daterangepicker",["jquery","moment","./daterangepicker-bs3.css"],
function(a){a("jquery");window .moment=a("moment"),a("./daterangepicker-bs3.css"),

(The source code of daterangepicker.js can be added in the middle) (I encountered it in the project at the moment, and it is usable; it is not clear yet and needs to be improved)   

Add

define("gallery/daterangepicker/1.3.7/daterangepicker-bs3.css",[],function(){
 seajs.importStyle(".daterangepicker{position:absolute;color:inherit;.........}"
 )})
 })
Copy after login

at the end 2. Use

During use, you need to pay attention to the parameter configuration of datetimepicker (this can be found on the official website). What I want to explain here is that you can download the source code on the official website and configure the parameters according to its demo to understand its various uses

Different parameters can be configured by selecting in the checkbox above. Here is a brief explanation of the parameters I used in the project and how to use them.

Due to the entire system of the project, there are double dates or single dates, or there are hours, minutes and seconds or no hours, minutes and seconds. Therefore, pairwise combinations are divided into four situations.

So I use the following:

/**
 * 日历
 * @param obj eles 日期输入框
 * @param boolean dobubble 是否为双日期(true)
 * @param boolean secondNot 有无时分秒(有则true)
 * @return none
 */
function calenders(eles,dobubble,secondNot){
 var singleNot,formatDate;
 if(dobubble ==true){
 singleNot = false;
 }else{
 singleNot = true;
 }
 if(secondNot ==true){
 formatDate = "YYYY-MM-DD HH:mm:ss";
 }else{
 formatDate = "YYYY-MM-DD";
 }
 
 $(eles).daterangepicker({
 "singleDatePicker": singleNot,//是否为单日期
 "timePicker": secondNot,//时间显示与否
 "timePicker24Hour": secondNot,//是否按24小时式来显示
 "timePickerSeconds": secondNot,//是否带秒
 "showDropdowns":true,//是否显示年月下拉选项,可以快速定位到哪一年哪一月
 "timePickerIncrement" :1,
 "linkedCalendars": false,//是否开始和结束连动,建议设为false,不然日期一直跳来跳去,首次使用者会觉得用户体检极度不佳
 "autoApply":true,//是否自动应用,不带时分秒的都可以实现在选择完日期后自动关闭,带时分秒时不会自动关闭
 "autoUpdateInput":false, //是否自动应用初始当前日期
 "locale": {
  "direction": "ltr",
  "format": formatDate,
  "separator": "~",
  "applyLabel": "Apply",
  "cancelLabel": "Cancel",
  "fromLabel": "From",
  "toLabel": "To",
  "customRangeLabel": "Custom",
  "daysOfWeek": [
  "Su",
  "Mo",
  "Tu",
  "We",
  "Th",
  "Fr",
  "Sa"
  ],
  "monthNames": [
  "一月",
   "二月",
   "三月",
   "四月",
   "五月",
   "六月",
   "七月",
   "八月",
   "九月",
   "十月",
   "十一月",
   "十二月"
  ],
  "firstDay": 1
 }
 }, function(start,end, label) {
 if(secondNot ==true&&dobubble ==true){
  $(eles).val($.trim(start.format('YYYY-MM-DD HH:mm:ss')+'~'+end.format('YYYY-MM-DD HH:mm:ss')));
 }else if(secondNot ==false&&dobubble ==true){
  $(eles).val($.trim(start.format('YYYY-MM-DD')+'~'+ end.format('YYYY-MM-DD')));
 }else if(secondNot ==false&&dobubble ==false){
  $(eles).val(start.format('YYYY-MM-DD'));
 }else if(secondNot ==true&&dobubble ==false){
  $(eles).val(start.format('YYYY-MM-DD HH:mm:ss'));
 }
 });
 //清空
 $(document).off('click','.clearBtns').on('click','.clearBtns',function(){
 $(eles).val('');
 })
}
Copy after login

Since daterangepicker does not have its own clearing function, and the project requirements sometimes require the date box to be empty, so I added a cross button behind the input box. As shown below, clearing is achieved

The code can be used as a reference (there are various ways to implement this)

<p class="input-group">
 <input type="text" name="extractionDate11" id="extractionDate11" class="form-control dateStart" placeholder="请选择起始时间" readonly size="30">
 <p class="input-group-addon clearBtns">x</p>
 </p>
 <span class="caret"></span>
Copy after login

And for quotes in various situations:

Single date without hours, minutes and seconds: calenders("#bgrq",false,false);

Single date with hours, minutes and seconds: calendars('#inputDate',false,true);

Double date without hours, minutes and seconds: calenders('#extractionDate11',true,false);

Double date with hours, minutes and seconds: calendars('#extractionDate11',true,true);

3. Problem Solving

1. Click on the drop-down date box, click on the blank space, the date box is closed, and the value is passed

Since the function of daterangepicker is: after clicking on the drop-down date box, click elsewhere on the page, the date box will be closed, and the previously selected date value will be automatically saved to the date box. This is what we are used to. It is equivalent to canceling, so make a modification in the source code:

Search the outsideClick method in the source code:

Replace this.hide() in it.

outsideClick: function(e) {
 var target = $(e.target);
 // if the page is clicked anywhere except within the daterangerpicker/button
 // itself then call this.hide()
 if (
 // ie modal dialog fix
 e.type == "focusin" ||
 target.closest(this.element).length ||
 target.closest(this.container).length ||
 target.closest('.calendar-table').length
 ) return;
 // this.hide();
 if (this.isShowing){
 $(document).off('.daterangepicker');
 $(window).off('.daterangepicker');
 this.container.hide();
 this.element.trigger('hide.daterangepicker', this);
 this.isShowing = false;
 }
 this.element.trigger('outsideClick.daterangepicker', this);
},
Copy after login

At the same time, the changes in the show method must be made, otherwise when the user selects dual dates, if he only selects one date and then clicks on the blank space, and the next time he clicks on the input box, an error will be reported and cannot be used anymore.

/*this.oldStartDate = this.startDate.clone();
this.oldEndDate = this.endDate.clone();
this.previousRightTime = this.endDate.clone();*/
this.oldStartDate = this.startDate;
this.oldEndDate = this.endDate;
this.previousRightTime = this.endDate;
Copy after login

2. The problem that the date is initially empty

Daterangepicker will automatically assign the current date to the bound input box at the beginning, that is, the parameter "autoUpdateInput":true/false, When it is true, the date will be automatically added. When false is selected, it will be initially empty. However, in some cases, it will not be automatically applied after selecting the date later. So we need to make some modifications (this is borrowed from this blog) Here we are a little clearer

(引用:在此我们可以使用autoUpdateInput属性,autoUpdateInput是用来打开和关闭daterangepicker选择时,是否自动传值到input[text] 这个DOM的属性,通过设置初始autoUpdateInput为false,可以实现初始值为空,这是在input中设置的placeholder才能正常显现出来。但是设置该属性之后,不管怎么选择daterangePikcer的日期,都不会有传值到input中,也就是没有办法正常显示选择的日期了,所以要在恰当的时刻,调用$(id).data('daterangepicker').autoUpdateInput=true,就可以了。作者最初设置为,最初默认值为空,当daterangepicker 的input发生点击时,autoUpadateInput=true,但是这时出现input不管是否选中日期,都会自动有值,所以为了修改这个问题,我在daterangepicker的源码中进行了修改,当然也可以重新更改需要的onclick事件。

在源码中,当autoUpdateInput设置为false之后,我们想要在点击确定,选中日期和点击range三个地方,将autoUpdateInput改变回来,所以,在三处设置this.autoUpdateInput=true属性)

1)在1210行左右的clickRange方法中:添加可以如下对照以下代码:

clickRange: function(e) {
 var label = e.target.getAttribute('data-range-key');
 this.chosenLabel = label;
 if (label == this.locale.customRangeLabel) {
 this.showCalendars();
 // } else {
 }else if (!this.endDate && date.isBefore(this.startDate)) {
 this.autoUpdateInput=true;
  //special case: clicking the same date for start/end,
  //but the time of the end date is before the start date
  this.setEndDate(this.startDate.clone());
 } else { // picking end
 this.autoUpdateInput=true;
 var dates = this.ranges[label];
 this.startDate = dates[0];
 this.endDate = dates[1];
 if (!this.timePicker) {
  this.startDate.startOf('day');
  this.endDate.endOf('day');
 }
 if (!this.alwaysShowCalendars)
  this.hideCalendars();
 this.clickApply();
 }
},
Copy after login

2)、在1340行左右,两处添加  this.autoUpdateInput=true; 请对照以下:

} else if (!this.endDate && date.isBefore(this.startDate)) {
 this.autoUpdateInput=true;
 //special case: clicking the same date for start/end,
 //but the time of the end date is before the start date
 this.setEndDate(this.startDate.clone());
} else { // picking end
 this.autoUpdateInput=true;
 if (this.timePicker) {
 var hour = parseInt(this.container.find('.right .hourselect').val(), 10);
 if (!this.timePicker24Hour) {
  var ampm = this.container.find('.right .ampmselect').val();
  if (ampm === 'PM' && hour < 12)
  hour += 12;
  if (ampm === 'AM' && hour === 12)
  hour = 0;
 }
Copy after login

3)、在1400行左右,给clickApply方法中添加  this.autoUpdateInput=true;

clickApply: function(e) {
 this.autoUpdateInput=true;
 this.hide();
 this.element.trigger('apply.daterangepicker', this);
 },相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
Copy after login

推荐阅读:

vue组件之间的传值方式

Angular4实现3d效果

The above is the detailed content of Detailed explanation of the use of daterangepicker control. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the mode function in C++ Detailed explanation of the mode function in C++ Nov 18, 2023 pm 03:08 PM

Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of remainder function in C++ Detailed explanation of remainder function in C++ Nov 18, 2023 pm 02:41 PM

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Jul 26, 2023 am 08:57 AM

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates. In Vue development, we often encounter situations where data needs to be updated asynchronously. For example, data needs to be updated immediately after modifying the DOM or related operations need to be performed immediately after the data is updated. The .nextTick function provided by Vue emerged to solve this type of problem. This article will introduce the usage of the Vue.nextTick function in detail, and combine it with code examples to illustrate its application in asynchronous updates. 1. Vue.nex

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

See all articles