daterangepicker.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. /**
  2. * @version: 3.1
  3. * @author: Dan Grossman http://www.dangrossman.info/
  4. * @copyright: Copyright (c) 2012-2019 Dan Grossman. All rights reserved.
  5. * @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php
  6. * @website: http://www.daterangepicker.com/
  7. */
  8. // Following the UMD template https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js
  9. (function (root, factory) {
  10. if (typeof define === 'function' && define.amd) {
  11. // AMD. Make globaly available as well
  12. define(['moment', 'jquery'], function (moment, jquery) {
  13. if (!jquery.fn) jquery.fn = {}; // webpack server rendering
  14. if (typeof moment !== 'function' && moment.hasOwnProperty('default')) moment = moment['default']
  15. return factory(moment, jquery);
  16. });
  17. } else if (typeof module === 'object' && module.exports) {
  18. // Node / Browserify
  19. //isomorphic issue
  20. var jQuery = (typeof window != 'undefined') ? window.jQuery : undefined;
  21. if (!jQuery) {
  22. jQuery = require('jquery');
  23. if (!jQuery.fn) jQuery.fn = {};
  24. }
  25. var moment = (typeof window != 'undefined' && typeof window.moment != 'undefined') ? window.moment : require('moment');
  26. module.exports = factory(moment, jQuery);
  27. } else {
  28. // Browser globals
  29. root.daterangepicker = factory(root.moment, root.jQuery);
  30. }
  31. }(this, function(moment, $) {
  32. var DateRangePicker = function(element, options, cb) {
  33. //default settings for options
  34. this.parentEl = 'body';
  35. this.element = $(element);
  36. this.startDate = moment().startOf('day');
  37. this.endDate = moment().endOf('day');
  38. this.minDate = false;
  39. this.maxDate = false;
  40. this.maxSpan = false;
  41. this.autoApply = false;
  42. this.singleDatePicker = false;
  43. this.showDropdowns = false;
  44. this.minYear = moment().subtract(100, 'year').format('YYYY');
  45. this.maxYear = moment().add(100, 'year').format('YYYY');
  46. this.showWeekNumbers = false;
  47. this.showISOWeekNumbers = false;
  48. this.showCustomRangeLabel = true;
  49. this.timePicker = false;
  50. this.timePicker24Hour = false;
  51. this.timePickerIncrement = 1;
  52. this.timePickerSeconds = false;
  53. this.linkedCalendars = true;
  54. this.autoUpdateInput = true;
  55. this.alwaysShowCalendars = false;
  56. this.ranges = {};
  57. this.opens = 'right';
  58. if (this.element.hasClass('pull-right'))
  59. this.opens = 'left';
  60. this.drops = 'down';
  61. if (this.element.hasClass('dropup'))
  62. this.drops = 'up';
  63. this.buttonClasses = 'btn btn-sm';
  64. this.applyButtonClasses = 'btn-primary';
  65. this.cancelButtonClasses = 'btn-default';
  66. this.locale = {
  67. direction: 'ltr',
  68. format: moment.localeData().longDateFormat('L'),
  69. separator: ' - ',
  70. applyLabel: 'Apply',
  71. cancelLabel: 'Cancel',
  72. weekLabel: 'W',
  73. customRangeLabel: 'Custom Range',
  74. daysOfWeek: moment.weekdaysMin(),
  75. monthNames: moment.monthsShort(),
  76. firstDay: moment.localeData().firstDayOfWeek()
  77. };
  78. this.callback = function() { };
  79. //some state information
  80. this.isShowing = false;
  81. this.leftCalendar = {};
  82. this.rightCalendar = {};
  83. //custom options from user
  84. if (typeof options !== 'object' || options === null)
  85. options = {};
  86. //allow setting options with data attributes
  87. //data-api options will be overwritten with custom javascript options
  88. options = $.extend(this.element.data(), options);
  89. //html template for the picker UI
  90. if (typeof options.template !== 'string' && !(options.template instanceof $))
  91. options.template =
  92. '<div class="daterangepicker">' +
  93. '<div class="ranges"></div>' +
  94. '<div class="drp-calendar left">' +
  95. '<div class="calendar-table"></div>' +
  96. '<div class="calendar-time"></div>' +
  97. '</div>' +
  98. '<div class="drp-calendar right">' +
  99. '<div class="calendar-table"></div>' +
  100. '<div class="calendar-time"></div>' +
  101. '</div>' +
  102. '<div class="drp-buttons">' +
  103. '<span class="drp-selected"></span>' +
  104. '<button class="cancelBtn" type="button"></button>' +
  105. '<button class="applyBtn" disabled="disabled" type="button"></button> ' +
  106. '</div>' +
  107. '</div>';
  108. this.parentEl = (options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl);
  109. this.container = $(options.template).appendTo(this.parentEl);
  110. //
  111. // handle all the possible options overriding defaults
  112. //
  113. if (typeof options.locale === 'object') {
  114. if (typeof options.locale.direction === 'string')
  115. this.locale.direction = options.locale.direction;
  116. if (typeof options.locale.format === 'string')
  117. this.locale.format = options.locale.format;
  118. if (typeof options.locale.separator === 'string')
  119. this.locale.separator = options.locale.separator;
  120. if (typeof options.locale.daysOfWeek === 'object')
  121. this.locale.daysOfWeek = options.locale.daysOfWeek.slice();
  122. if (typeof options.locale.monthNames === 'object')
  123. this.locale.monthNames = options.locale.monthNames.slice();
  124. if (typeof options.locale.firstDay === 'number')
  125. this.locale.firstDay = options.locale.firstDay;
  126. if (typeof options.locale.applyLabel === 'string')
  127. this.locale.applyLabel = options.locale.applyLabel;
  128. if (typeof options.locale.cancelLabel === 'string')
  129. this.locale.cancelLabel = options.locale.cancelLabel;
  130. if (typeof options.locale.weekLabel === 'string')
  131. this.locale.weekLabel = options.locale.weekLabel;
  132. if (typeof options.locale.customRangeLabel === 'string'){
  133. //Support unicode chars in the custom range name.
  134. var elem = document.createElement('textarea');
  135. elem.innerHTML = options.locale.customRangeLabel;
  136. var rangeHtml = elem.value;
  137. this.locale.customRangeLabel = rangeHtml;
  138. }
  139. }
  140. this.container.addClass(this.locale.direction);
  141. if (typeof options.startDate === 'string')
  142. this.startDate = moment(options.startDate, this.locale.format);
  143. if (typeof options.endDate === 'string')
  144. this.endDate = moment(options.endDate, this.locale.format);
  145. if (typeof options.minDate === 'string')
  146. this.minDate = moment(options.minDate, this.locale.format);
  147. if (typeof options.maxDate === 'string')
  148. this.maxDate = moment(options.maxDate, this.locale.format);
  149. if (typeof options.startDate === 'object')
  150. this.startDate = moment(options.startDate);
  151. if (typeof options.endDate === 'object')
  152. this.endDate = moment(options.endDate);
  153. if (typeof options.minDate === 'object')
  154. this.minDate = moment(options.minDate);
  155. if (typeof options.maxDate === 'object')
  156. this.maxDate = moment(options.maxDate);
  157. // sanity check for bad options
  158. if (this.minDate && this.startDate.isBefore(this.minDate))
  159. this.startDate = this.minDate.clone();
  160. // sanity check for bad options
  161. if (this.maxDate && this.endDate.isAfter(this.maxDate))
  162. this.endDate = this.maxDate.clone();
  163. if (typeof options.applyButtonClasses === 'string')
  164. this.applyButtonClasses = options.applyButtonClasses;
  165. if (typeof options.applyClass === 'string') //backwards compat
  166. this.applyButtonClasses = options.applyClass;
  167. if (typeof options.cancelButtonClasses === 'string')
  168. this.cancelButtonClasses = options.cancelButtonClasses;
  169. if (typeof options.cancelClass === 'string') //backwards compat
  170. this.cancelButtonClasses = options.cancelClass;
  171. if (typeof options.maxSpan === 'object')
  172. this.maxSpan = options.maxSpan;
  173. if (typeof options.dateLimit === 'object') //backwards compat
  174. this.maxSpan = options.dateLimit;
  175. if (typeof options.opens === 'string')
  176. this.opens = options.opens;
  177. if (typeof options.drops === 'string')
  178. this.drops = options.drops;
  179. if (typeof options.showWeekNumbers === 'boolean')
  180. this.showWeekNumbers = options.showWeekNumbers;
  181. if (typeof options.showISOWeekNumbers === 'boolean')
  182. this.showISOWeekNumbers = options.showISOWeekNumbers;
  183. if (typeof options.buttonClasses === 'string')
  184. this.buttonClasses = options.buttonClasses;
  185. if (typeof options.buttonClasses === 'object')
  186. this.buttonClasses = options.buttonClasses.join(' ');
  187. if (typeof options.showDropdowns === 'boolean')
  188. this.showDropdowns = options.showDropdowns;
  189. if (typeof options.minYear === 'number')
  190. this.minYear = options.minYear;
  191. if (typeof options.maxYear === 'number')
  192. this.maxYear = options.maxYear;
  193. if (typeof options.showCustomRangeLabel === 'boolean')
  194. this.showCustomRangeLabel = options.showCustomRangeLabel;
  195. if (typeof options.singleDatePicker === 'boolean') {
  196. this.singleDatePicker = options.singleDatePicker;
  197. if (this.singleDatePicker)
  198. this.endDate = this.startDate.clone();
  199. }
  200. if (typeof options.timePicker === 'boolean')
  201. this.timePicker = options.timePicker;
  202. if (typeof options.timePickerSeconds === 'boolean')
  203. this.timePickerSeconds = options.timePickerSeconds;
  204. if (typeof options.timePickerIncrement === 'number')
  205. this.timePickerIncrement = options.timePickerIncrement;
  206. if (typeof options.timePicker24Hour === 'boolean')
  207. this.timePicker24Hour = options.timePicker24Hour;
  208. if (typeof options.autoApply === 'boolean')
  209. this.autoApply = options.autoApply;
  210. if (typeof options.autoUpdateInput === 'boolean')
  211. this.autoUpdateInput = options.autoUpdateInput;
  212. if (typeof options.linkedCalendars === 'boolean')
  213. this.linkedCalendars = options.linkedCalendars;
  214. if (typeof options.isInvalidDate === 'function')
  215. this.isInvalidDate = options.isInvalidDate;
  216. if (typeof options.isCustomDate === 'function')
  217. this.isCustomDate = options.isCustomDate;
  218. if (typeof options.alwaysShowCalendars === 'boolean')
  219. this.alwaysShowCalendars = options.alwaysShowCalendars;
  220. // update day names order to firstDay
  221. if (this.locale.firstDay != 0) {
  222. var iterator = this.locale.firstDay;
  223. while (iterator > 0) {
  224. this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
  225. iterator--;
  226. }
  227. }
  228. var start, end, range;
  229. //if no start/end dates set, check if an input element contains initial values
  230. if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
  231. if ($(this.element).is(':text')) {
  232. var val = $(this.element).val(),
  233. split = val.split(this.locale.separator);
  234. start = end = null;
  235. if (split.length == 2) {
  236. start = moment(split[0], this.locale.format);
  237. end = moment(split[1], this.locale.format);
  238. } else if (this.singleDatePicker && val !== "") {
  239. start = moment(val, this.locale.format);
  240. end = moment(val, this.locale.format);
  241. }
  242. if (start !== null && end !== null) {
  243. this.setStartDate(start);
  244. this.setEndDate(end);
  245. }
  246. }
  247. }
  248. if (typeof options.ranges === 'object') {
  249. for (range in options.ranges) {
  250. if (typeof options.ranges[range][0] === 'string')
  251. start = moment(options.ranges[range][0], this.locale.format);
  252. else
  253. start = moment(options.ranges[range][0]);
  254. if (typeof options.ranges[range][1] === 'string')
  255. end = moment(options.ranges[range][1], this.locale.format);
  256. else
  257. end = moment(options.ranges[range][1]);
  258. // If the start or end date exceed those allowed by the minDate or maxSpan
  259. // options, shorten the range to the allowable period.
  260. if (this.minDate && start.isBefore(this.minDate))
  261. start = this.minDate.clone();
  262. var maxDate = this.maxDate;
  263. if (this.maxSpan && maxDate && start.clone().add(this.maxSpan).isAfter(maxDate))
  264. maxDate = start.clone().add(this.maxSpan);
  265. if (maxDate && end.isAfter(maxDate))
  266. end = maxDate.clone();
  267. // If the end of the range is before the minimum or the start of the range is
  268. // after the maximum, don't display this range option at all.
  269. if ((this.minDate && end.isBefore(this.minDate, this.timepicker ? 'minute' : 'day'))
  270. || (maxDate && start.isAfter(maxDate, this.timepicker ? 'minute' : 'day')))
  271. continue;
  272. //Support unicode chars in the range names.
  273. var elem = document.createElement('textarea');
  274. elem.innerHTML = range;
  275. var rangeHtml = elem.value;
  276. this.ranges[rangeHtml] = [start, end];
  277. }
  278. var list = '<ul>';
  279. for (range in this.ranges) {
  280. list += '<li data-range-key="' + range + '">' + range + '</li>';
  281. }
  282. if (this.showCustomRangeLabel) {
  283. list += '<li data-range-key="' + this.locale.customRangeLabel + '">' + this.locale.customRangeLabel + '</li>';
  284. }
  285. list += '</ul>';
  286. this.container.find('.ranges').prepend(list);
  287. }
  288. if (typeof cb === 'function') {
  289. this.callback = cb;
  290. }
  291. if (!this.timePicker) {
  292. this.startDate = this.startDate.startOf('day');
  293. this.endDate = this.endDate.endOf('day');
  294. this.container.find('.calendar-time').hide();
  295. }
  296. //can't be used together for now
  297. if (this.timePicker && this.autoApply)
  298. this.autoApply = false;
  299. if (this.autoApply) {
  300. this.container.addClass('auto-apply');
  301. }
  302. if (typeof options.ranges === 'object')
  303. this.container.addClass('show-ranges');
  304. if (this.singleDatePicker) {
  305. this.container.addClass('single');
  306. this.container.find('.drp-calendar.left').addClass('single');
  307. this.container.find('.drp-calendar.left').show();
  308. this.container.find('.drp-calendar.right').hide();
  309. if (!this.timePicker && this.autoApply) {
  310. this.container.addClass('auto-apply');
  311. }
  312. }
  313. if ((typeof options.ranges === 'undefined' && !this.singleDatePicker) || this.alwaysShowCalendars) {
  314. this.container.addClass('show-calendar');
  315. }
  316. this.container.addClass('opens' + this.opens);
  317. //apply CSS classes and labels to buttons
  318. this.container.find('.applyBtn, .cancelBtn').addClass(this.buttonClasses);
  319. if (this.applyButtonClasses.length)
  320. this.container.find('.applyBtn').addClass(this.applyButtonClasses);
  321. if (this.cancelButtonClasses.length)
  322. this.container.find('.cancelBtn').addClass(this.cancelButtonClasses);
  323. this.container.find('.applyBtn').html(this.locale.applyLabel);
  324. this.container.find('.cancelBtn').html(this.locale.cancelLabel);
  325. //
  326. // event listeners
  327. //
  328. this.container.find('.drp-calendar')
  329. .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this))
  330. .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this))
  331. .on('mousedown.daterangepicker', 'td.available', $.proxy(this.clickDate, this))
  332. .on('mouseenter.daterangepicker', 'td.available', $.proxy(this.hoverDate, this))
  333. .on('change.daterangepicker', 'select.yearselect', $.proxy(this.monthOrYearChanged, this))
  334. .on('change.daterangepicker', 'select.monthselect', $.proxy(this.monthOrYearChanged, this))
  335. .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.secondselect,select.ampmselect', $.proxy(this.timeChanged, this));
  336. this.container.find('.ranges')
  337. .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this));
  338. this.container.find('.drp-buttons')
  339. .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this))
  340. .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this));
  341. if (this.element.is('input') || this.element.is('button')) {
  342. this.element.on({
  343. 'click.daterangepicker': $.proxy(this.show, this),
  344. 'focus.daterangepicker': $.proxy(this.show, this),
  345. 'keyup.daterangepicker': $.proxy(this.elementChanged, this),
  346. 'keydown.daterangepicker': $.proxy(this.keydown, this) //IE 11 compatibility
  347. });
  348. } else {
  349. this.element.on('click.daterangepicker', $.proxy(this.toggle, this));
  350. this.element.on('keydown.daterangepicker', $.proxy(this.toggle, this));
  351. }
  352. //
  353. // if attached to a text input, set the initial value
  354. //
  355. this.updateElement();
  356. };
  357. DateRangePicker.prototype = {
  358. constructor: DateRangePicker,
  359. setStartDate: function(startDate) {
  360. if (typeof startDate === 'string')
  361. this.startDate = moment(startDate, this.locale.format);
  362. if (typeof startDate === 'object')
  363. this.startDate = moment(startDate);
  364. if (!this.timePicker)
  365. this.startDate = this.startDate.startOf('day');
  366. if (this.timePicker && this.timePickerIncrement)
  367. this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
  368. if (this.minDate && this.startDate.isBefore(this.minDate)) {
  369. this.startDate = this.minDate.clone();
  370. if (this.timePicker && this.timePickerIncrement)
  371. this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
  372. }
  373. if (this.maxDate && this.startDate.isAfter(this.maxDate)) {
  374. this.startDate = this.maxDate.clone();
  375. if (this.timePicker && this.timePickerIncrement)
  376. this.startDate.minute(Math.floor(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
  377. }
  378. if (!this.isShowing)
  379. this.updateElement();
  380. this.updateMonthsInView();
  381. },
  382. setEndDate: function(endDate) {
  383. if (typeof endDate === 'string')
  384. this.endDate = moment(endDate, this.locale.format);
  385. if (typeof endDate === 'object')
  386. this.endDate = moment(endDate);
  387. if (!this.timePicker)
  388. this.endDate = this.endDate.endOf('day');
  389. if (this.timePicker && this.timePickerIncrement)
  390. this.endDate.minute(Math.round(this.endDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
  391. if (this.endDate.isBefore(this.startDate))
  392. this.endDate = this.startDate.clone();
  393. if (this.maxDate && this.endDate.isAfter(this.maxDate))
  394. this.endDate = this.maxDate.clone();
  395. if (this.maxSpan && this.startDate.clone().add(this.maxSpan).isBefore(this.endDate))
  396. this.endDate = this.startDate.clone().add(this.maxSpan);
  397. this.previousRightTime = this.endDate.clone();
  398. this.container.find('.drp-selected').html(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
  399. if (!this.isShowing)
  400. this.updateElement();
  401. this.updateMonthsInView();
  402. },
  403. isInvalidDate: function() {
  404. return false;
  405. },
  406. isCustomDate: function() {
  407. return false;
  408. },
  409. updateView: function() {
  410. if (this.timePicker) {
  411. this.renderTimePicker('left');
  412. this.renderTimePicker('right');
  413. if (!this.endDate) {
  414. this.container.find('.right .calendar-time select').prop('disabled', true).addClass('disabled');
  415. } else {
  416. this.container.find('.right .calendar-time select').prop('disabled', false).removeClass('disabled');
  417. }
  418. }
  419. if (this.endDate)
  420. this.container.find('.drp-selected').html(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
  421. this.updateMonthsInView();
  422. this.updateCalendars();
  423. this.updateFormInputs();
  424. },
  425. updateMonthsInView: function() {
  426. if (this.endDate) {
  427. //if both dates are visible already, do nothing
  428. if (!this.singleDatePicker && this.leftCalendar.month && this.rightCalendar.month &&
  429. (this.startDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.startDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
  430. &&
  431. (this.endDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.endDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
  432. ) {
  433. return;
  434. }
  435. this.leftCalendar.month = this.startDate.clone().date(2);
  436. if (!this.linkedCalendars && (this.endDate.month() != this.startDate.month() || this.endDate.year() != this.startDate.year())) {
  437. this.rightCalendar.month = this.endDate.clone().date(2);
  438. } else {
  439. this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
  440. }
  441. } else {
  442. if (this.leftCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM') && this.rightCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM')) {
  443. this.leftCalendar.month = this.startDate.clone().date(2);
  444. this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
  445. }
  446. }
  447. if (this.maxDate && this.linkedCalendars && !this.singleDatePicker && this.rightCalendar.month > this.maxDate) {
  448. this.rightCalendar.month = this.maxDate.clone().date(2);
  449. this.leftCalendar.month = this.maxDate.clone().date(2).subtract(1, 'month');
  450. }
  451. },
  452. updateCalendars: function() {
  453. if (this.timePicker) {
  454. var hour, minute, second;
  455. if (this.endDate) {
  456. hour = parseInt(this.container.find('.left .hourselect').val(), 10);
  457. minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
  458. if (isNaN(minute)) {
  459. minute = parseInt(this.container.find('.left .minuteselect option:last').val(), 10);
  460. }
  461. second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
  462. if (!this.timePicker24Hour) {
  463. var ampm = this.container.find('.left .ampmselect').val();
  464. if (ampm === 'PM' && hour < 12)
  465. hour += 12;
  466. if (ampm === 'AM' && hour === 12)
  467. hour = 0;
  468. }
  469. } else {
  470. hour = parseInt(this.container.find('.right .hourselect').val(), 10);
  471. minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
  472. if (isNaN(minute)) {
  473. minute = parseInt(this.container.find('.right .minuteselect option:last').val(), 10);
  474. }
  475. second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
  476. if (!this.timePicker24Hour) {
  477. var ampm = this.container.find('.right .ampmselect').val();
  478. if (ampm === 'PM' && hour < 12)
  479. hour += 12;
  480. if (ampm === 'AM' && hour === 12)
  481. hour = 0;
  482. }
  483. }
  484. this.leftCalendar.month.hour(hour).minute(minute).second(second);
  485. this.rightCalendar.month.hour(hour).minute(minute).second(second);
  486. }
  487. this.renderCalendar('left');
  488. this.renderCalendar('right');
  489. //highlight any predefined range matching the current start and end dates
  490. this.container.find('.ranges li').removeClass('active');
  491. if (this.endDate == null) return;
  492. this.calculateChosenLabel();
  493. },
  494. renderCalendar: function(side) {
  495. //
  496. // Build the matrix of dates that will populate the calendar
  497. //
  498. var calendar = side == 'left' ? this.leftCalendar : this.rightCalendar;
  499. var month = calendar.month.month();
  500. var year = calendar.month.year();
  501. var hour = calendar.month.hour();
  502. var minute = calendar.month.minute();
  503. var second = calendar.month.second();
  504. var daysInMonth = moment([year, month]).daysInMonth();
  505. var firstDay = moment([year, month, 1]);
  506. var lastDay = moment([year, month, daysInMonth]);
  507. var lastMonth = moment(firstDay).subtract(1, 'month').month();
  508. var lastYear = moment(firstDay).subtract(1, 'month').year();
  509. var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
  510. var dayOfWeek = firstDay.day();
  511. //initialize a 6 rows x 7 columns array for the calendar
  512. var calendar = [];
  513. calendar.firstDay = firstDay;
  514. calendar.lastDay = lastDay;
  515. for (var i = 0; i < 6; i++) {
  516. calendar[i] = [];
  517. }
  518. //populate the calendar with date objects
  519. var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
  520. if (startDay > daysInLastMonth)
  521. startDay -= 7;
  522. if (dayOfWeek == this.locale.firstDay)
  523. startDay = daysInLastMonth - 6;
  524. var curDate = moment([lastYear, lastMonth, startDay, 12, minute, second]);
  525. var col, row;
  526. for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) {
  527. if (i > 0 && col % 7 === 0) {
  528. col = 0;
  529. row++;
  530. }
  531. calendar[row][col] = curDate.clone().hour(hour).minute(minute).second(second);
  532. curDate.hour(12);
  533. if (this.minDate && calendar[row][col].format('YYYY-MM-DD') == this.minDate.format('YYYY-MM-DD') && calendar[row][col].isBefore(this.minDate) && side == 'left') {
  534. calendar[row][col] = this.minDate.clone();
  535. }
  536. if (this.maxDate && calendar[row][col].format('YYYY-MM-DD') == this.maxDate.format('YYYY-MM-DD') && calendar[row][col].isAfter(this.maxDate) && side == 'right') {
  537. calendar[row][col] = this.maxDate.clone();
  538. }
  539. }
  540. //make the calendar object available to hoverDate/clickDate
  541. if (side == 'left') {
  542. this.leftCalendar.calendar = calendar;
  543. } else {
  544. this.rightCalendar.calendar = calendar;
  545. }
  546. //
  547. // Display the calendar
  548. //
  549. var minDate = side == 'left' ? this.minDate : this.startDate;
  550. var maxDate = this.maxDate;
  551. var selected = side == 'left' ? this.startDate : this.endDate;
  552. var arrow = this.locale.direction == 'ltr' ? {left: 'chevron-left', right: 'chevron-right'} : {left: 'chevron-right', right: 'chevron-left'};
  553. var html = '<table class="table-condensed">';
  554. html += '<thead>';
  555. html += '<tr>';
  556. // add empty cell for week number
  557. if (this.showWeekNumbers || this.showISOWeekNumbers)
  558. html += '<th></th>';
  559. if ((!minDate || minDate.isBefore(calendar.firstDay)) && (!this.linkedCalendars || side == 'left')) {
  560. html += '<th class="prev available"><span></span></th>';
  561. } else {
  562. html += '<th></th>';
  563. }
  564. var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
  565. if (this.showDropdowns) {
  566. var currentMonth = calendar[1][1].month();
  567. var currentYear = calendar[1][1].year();
  568. var maxYear = (maxDate && maxDate.year()) || (this.maxYear);
  569. var minYear = (minDate && minDate.year()) || (this.minYear);
  570. var inMinYear = currentYear == minYear;
  571. var inMaxYear = currentYear == maxYear;
  572. var monthHtml = '<select class="monthselect">';
  573. for (var m = 0; m < 12; m++) {
  574. if ((!inMinYear || (minDate && m >= minDate.month())) && (!inMaxYear || (maxDate && m <= maxDate.month()))) {
  575. monthHtml += "<option value='" + m + "'" +
  576. (m === currentMonth ? " selected='selected'" : "") +
  577. ">" + this.locale.monthNames[m] + "</option>";
  578. } else {
  579. monthHtml += "<option value='" + m + "'" +
  580. (m === currentMonth ? " selected='selected'" : "") +
  581. " disabled='disabled'>" + this.locale.monthNames[m] + "</option>";
  582. }
  583. }
  584. monthHtml += "</select>";
  585. var yearHtml = '<select class="yearselect">';
  586. for (var y = minYear; y <= maxYear; y++) {
  587. yearHtml += '<option value="' + y + '"' +
  588. (y === currentYear ? ' selected="selected"' : '') +
  589. '>' + y + '</option>';
  590. }
  591. yearHtml += '</select>';
  592. dateHtml = monthHtml + yearHtml;
  593. }
  594. html += '<th colspan="5" class="month">' + dateHtml + '</th>';
  595. if ((!maxDate || maxDate.isAfter(calendar.lastDay)) && (!this.linkedCalendars || side == 'right' || this.singleDatePicker)) {
  596. html += '<th class="next available"><span></span></th>';
  597. } else {
  598. html += '<th></th>';
  599. }
  600. html += '</tr>';
  601. html += '<tr>';
  602. // add week number label
  603. if (this.showWeekNumbers || this.showISOWeekNumbers)
  604. html += '<th class="week">' + this.locale.weekLabel + '</th>';
  605. $.each(this.locale.daysOfWeek, function(index, dayOfWeek) {
  606. html += '<th>' + dayOfWeek + '</th>';
  607. });
  608. html += '</tr>';
  609. html += '</thead>';
  610. html += '<tbody>';
  611. //adjust maxDate to reflect the maxSpan setting in order to
  612. //grey out end dates beyond the maxSpan
  613. if (this.endDate == null && this.maxSpan) {
  614. var maxLimit = this.startDate.clone().add(this.maxSpan).endOf('day');
  615. if (!maxDate || maxLimit.isBefore(maxDate)) {
  616. maxDate = maxLimit;
  617. }
  618. }
  619. for (var row = 0; row < 6; row++) {
  620. html += '<tr>';
  621. // add week number
  622. if (this.showWeekNumbers)
  623. html += '<td class="week">' + calendar[row][0].week() + '</td>';
  624. else if (this.showISOWeekNumbers)
  625. html += '<td class="week">' + calendar[row][0].isoWeek() + '</td>';
  626. for (var col = 0; col < 7; col++) {
  627. var classes = [];
  628. //highlight today's date
  629. if (calendar[row][col].isSame(new Date(), "day"))
  630. classes.push('today');
  631. //highlight weekends
  632. if (calendar[row][col].isoWeekday() > 5)
  633. classes.push('weekend');
  634. //grey out the dates in other months displayed at beginning and end of this calendar
  635. if (calendar[row][col].month() != calendar[1][1].month())
  636. classes.push('off', 'ends');
  637. //don't allow selection of dates before the minimum date
  638. if (this.minDate && calendar[row][col].isBefore(this.minDate, 'day'))
  639. classes.push('off', 'disabled');
  640. //don't allow selection of dates after the maximum date
  641. if (maxDate && calendar[row][col].isAfter(maxDate, 'day'))
  642. classes.push('off', 'disabled');
  643. //don't allow selection of date if a custom function decides it's invalid
  644. if (this.isInvalidDate(calendar[row][col]))
  645. classes.push('off', 'disabled');
  646. //highlight the currently selected start date
  647. if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD'))
  648. classes.push('active', 'start-date');
  649. //highlight the currently selected end date
  650. if (this.endDate != null && calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD'))
  651. classes.push('active', 'end-date');
  652. //highlight dates in-between the selected dates
  653. if (this.endDate != null && calendar[row][col] > this.startDate && calendar[row][col] < this.endDate)
  654. classes.push('in-range');
  655. //apply custom classes for this date
  656. var isCustom = this.isCustomDate(calendar[row][col]);
  657. if (isCustom !== false) {
  658. if (typeof isCustom === 'string')
  659. classes.push(isCustom);
  660. else
  661. Array.prototype.push.apply(classes, isCustom);
  662. }
  663. var cname = '', disabled = false;
  664. for (var i = 0; i < classes.length; i++) {
  665. cname += classes[i] + ' ';
  666. if (classes[i] == 'disabled')
  667. disabled = true;
  668. }
  669. if (!disabled)
  670. cname += 'available';
  671. html += '<td class="' + cname.replace(/^\s+|\s+$/g, '') + '" data-title="' + 'r' + row + 'c' + col + '">' + calendar[row][col].date() + '</td>';
  672. }
  673. html += '</tr>';
  674. }
  675. html += '</tbody>';
  676. html += '</table>';
  677. this.container.find('.drp-calendar.' + side + ' .calendar-table').html(html);
  678. },
  679. renderTimePicker: function(side) {
  680. // Don't bother updating the time picker if it's currently disabled
  681. // because an end date hasn't been clicked yet
  682. if (side == 'right' && !this.endDate) return;
  683. var html, selected, minDate, maxDate = this.maxDate;
  684. if (this.maxSpan && (!this.maxDate || this.startDate.clone().add(this.maxSpan).isBefore(this.maxDate)))
  685. maxDate = this.startDate.clone().add(this.maxSpan);
  686. if (side == 'left') {
  687. selected = this.startDate.clone();
  688. minDate = this.minDate;
  689. } else if (side == 'right') {
  690. selected = this.endDate.clone();
  691. minDate = this.startDate;
  692. //Preserve the time already selected
  693. var timeSelector = this.container.find('.drp-calendar.right .calendar-time');
  694. if (timeSelector.html() != '') {
  695. selected.hour(!isNaN(selected.hour()) ? selected.hour() : timeSelector.find('.hourselect option:selected').val());
  696. selected.minute(!isNaN(selected.minute()) ? selected.minute() : timeSelector.find('.minuteselect option:selected').val());
  697. selected.second(!isNaN(selected.second()) ? selected.second() : timeSelector.find('.secondselect option:selected').val());
  698. if (!this.timePicker24Hour) {
  699. var ampm = timeSelector.find('.ampmselect option:selected').val();
  700. if (ampm === 'PM' && selected.hour() < 12)
  701. selected.hour(selected.hour() + 12);
  702. if (ampm === 'AM' && selected.hour() === 12)
  703. selected.hour(0);
  704. }
  705. }
  706. if (selected.isBefore(this.startDate))
  707. selected = this.startDate.clone();
  708. if (maxDate && selected.isAfter(maxDate))
  709. selected = maxDate.clone();
  710. }
  711. //
  712. // hours
  713. //
  714. html = '<select class="hourselect">';
  715. var start = this.timePicker24Hour ? 0 : 1;
  716. var end = this.timePicker24Hour ? 23 : 12;
  717. for (var i = start; i <= end; i++) {
  718. var i_in_24 = i;
  719. if (!this.timePicker24Hour)
  720. i_in_24 = selected.hour() >= 12 ? (i == 12 ? 12 : i + 12) : (i == 12 ? 0 : i);
  721. var time = selected.clone().hour(i_in_24);
  722. var disabled = false;
  723. if (minDate && time.minute(59).isBefore(minDate))
  724. disabled = true;
  725. if (maxDate && time.minute(0).isAfter(maxDate))
  726. disabled = true;
  727. if (i_in_24 == selected.hour() && !disabled) {
  728. html += '<option value="' + i + '" selected="selected">' + i + '</option>';
  729. } else if (disabled) {
  730. html += '<option value="' + i + '" disabled="disabled" class="disabled">' + i + '</option>';
  731. } else {
  732. html += '<option value="' + i + '">' + i + '</option>';
  733. }
  734. }
  735. html += '</select> ';
  736. //
  737. // minutes
  738. //
  739. html += ': <select class="minuteselect">';
  740. for (var i = 0; i < 60; i += this.timePickerIncrement) {
  741. var padded = i < 10 ? '0' + i : i;
  742. var time = selected.clone().minute(i);
  743. var disabled = false;
  744. if (minDate && time.second(59).isBefore(minDate))
  745. disabled = true;
  746. if (maxDate && time.second(0).isAfter(maxDate))
  747. disabled = true;
  748. if (selected.minute() == i && !disabled) {
  749. html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
  750. } else if (disabled) {
  751. html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
  752. } else {
  753. html += '<option value="' + i + '">' + padded + '</option>';
  754. }
  755. }
  756. html += '</select> ';
  757. //
  758. // seconds
  759. //
  760. if (this.timePickerSeconds) {
  761. html += ': <select class="secondselect">';
  762. for (var i = 0; i < 60; i++) {
  763. var padded = i < 10 ? '0' + i : i;
  764. var time = selected.clone().second(i);
  765. var disabled = false;
  766. if (minDate && time.isBefore(minDate))
  767. disabled = true;
  768. if (maxDate && time.isAfter(maxDate))
  769. disabled = true;
  770. if (selected.second() == i && !disabled) {
  771. html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
  772. } else if (disabled) {
  773. html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
  774. } else {
  775. html += '<option value="' + i + '">' + padded + '</option>';
  776. }
  777. }
  778. html += '</select> ';
  779. }
  780. //
  781. // AM/PM
  782. //
  783. if (!this.timePicker24Hour) {
  784. html += '<select class="ampmselect">';
  785. var am_html = '';
  786. var pm_html = '';
  787. if (minDate && selected.clone().hour(12).minute(0).second(0).isBefore(minDate))
  788. am_html = ' disabled="disabled" class="disabled"';
  789. if (maxDate && selected.clone().hour(0).minute(0).second(0).isAfter(maxDate))
  790. pm_html = ' disabled="disabled" class="disabled"';
  791. if (selected.hour() >= 12) {
  792. html += '<option value="AM"' + am_html + '>AM</option><option value="PM" selected="selected"' + pm_html + '>PM</option>';
  793. } else {
  794. html += '<option value="AM" selected="selected"' + am_html + '>AM</option><option value="PM"' + pm_html + '>PM</option>';
  795. }
  796. html += '</select>';
  797. }
  798. this.container.find('.drp-calendar.' + side + ' .calendar-time').html(html);
  799. },
  800. updateFormInputs: function() {
  801. if (this.singleDatePicker || (this.endDate && (this.startDate.isBefore(this.endDate) || this.startDate.isSame(this.endDate)))) {
  802. this.container.find('button.applyBtn').prop('disabled', false);
  803. } else {
  804. this.container.find('button.applyBtn').prop('disabled', true);
  805. }
  806. },
  807. move: function() {
  808. var parentOffset = { top: 0, left: 0 },
  809. containerTop,
  810. drops = this.drops;
  811. var parentRightEdge = $(window).width();
  812. if (!this.parentEl.is('body')) {
  813. parentOffset = {
  814. top: this.parentEl.offset().top - this.parentEl.scrollTop(),
  815. left: this.parentEl.offset().left - this.parentEl.scrollLeft()
  816. };
  817. parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left;
  818. }
  819. switch (drops) {
  820. case 'auto':
  821. containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top;
  822. if (containerTop + this.container.outerHeight() >= this.parentEl[0].scrollHeight) {
  823. containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top;
  824. drops = 'up';
  825. }
  826. break;
  827. case 'up':
  828. containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top;
  829. break;
  830. default:
  831. containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top;
  832. break;
  833. }
  834. // Force the container to it's actual width
  835. this.container.css({
  836. top: 0,
  837. left: 0,
  838. right: 'auto'
  839. });
  840. var containerWidth = this.container.outerWidth();
  841. this.container.toggleClass('drop-up', drops == 'up');
  842. if (this.opens == 'left') {
  843. var containerRight = parentRightEdge - this.element.offset().left - this.element.outerWidth();
  844. if (containerWidth + containerRight > $(window).width()) {
  845. this.container.css({
  846. top: containerTop,
  847. right: 'auto',
  848. left: 9
  849. });
  850. } else {
  851. this.container.css({
  852. top: containerTop,
  853. right: containerRight,
  854. left: 'auto'
  855. });
  856. }
  857. } else if (this.opens == 'center') {
  858. var containerLeft = this.element.offset().left - parentOffset.left + this.element.outerWidth() / 2
  859. - containerWidth / 2;
  860. if (containerLeft < 0) {
  861. this.container.css({
  862. top: containerTop,
  863. right: 'auto',
  864. left: 9
  865. });
  866. } else if (containerLeft + containerWidth > $(window).width()) {
  867. this.container.css({
  868. top: containerTop,
  869. left: 'auto',
  870. right: 0
  871. });
  872. } else {
  873. this.container.css({
  874. top: containerTop,
  875. left: containerLeft,
  876. right: 'auto'
  877. });
  878. }
  879. } else {
  880. var containerLeft = this.element.offset().left - parentOffset.left;
  881. if (containerLeft + containerWidth > $(window).width()) {
  882. this.container.css({
  883. top: containerTop,
  884. left: 'auto',
  885. right: 0
  886. });
  887. } else {
  888. this.container.css({
  889. top: containerTop,
  890. left: containerLeft,
  891. right: 'auto'
  892. });
  893. }
  894. }
  895. },
  896. show: function(e) {
  897. if (this.isShowing) return;
  898. // Create a click proxy that is private to this instance of datepicker, for unbinding
  899. this._outsideClickProxy = $.proxy(function(e) { this.outsideClick(e); }, this);
  900. // Bind global datepicker mousedown for hiding and
  901. $(document)
  902. .on('mousedown.daterangepicker', this._outsideClickProxy)
  903. // also support mobile devices
  904. .on('touchend.daterangepicker', this._outsideClickProxy)
  905. // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
  906. .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
  907. // and also close when focus changes to outside the picker (eg. tabbing between controls)
  908. .on('focusin.daterangepicker', this._outsideClickProxy);
  909. // Reposition the picker if the window is resized while it's open
  910. $(window).on('resize.daterangepicker', $.proxy(function(e) { this.move(e); }, this));
  911. this.oldStartDate = this.startDate.clone();
  912. this.oldEndDate = this.endDate.clone();
  913. this.previousRightTime = this.endDate.clone();
  914. this.updateView();
  915. this.container.show();
  916. this.move();
  917. this.element.trigger('show.daterangepicker', this);
  918. this.isShowing = true;
  919. },
  920. hide: function(e) {
  921. if (!this.isShowing) return;
  922. //incomplete date selection, revert to last values
  923. if (!this.endDate) {
  924. this.startDate = this.oldStartDate.clone();
  925. this.endDate = this.oldEndDate.clone();
  926. }
  927. //if a new date range was selected, invoke the user callback function
  928. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  929. this.callback(this.startDate.clone(), this.endDate.clone(), this.chosenLabel);
  930. //if picker is attached to a text input, update it
  931. this.updateElement();
  932. $(document).off('.daterangepicker');
  933. $(window).off('.daterangepicker');
  934. this.container.hide();
  935. this.element.trigger('hide.daterangepicker', this);
  936. this.isShowing = false;
  937. },
  938. toggle: function(e) {
  939. if (this.isShowing) {
  940. this.hide();
  941. } else {
  942. this.show();
  943. }
  944. },
  945. outsideClick: function(e) {
  946. var target = $(e.target);
  947. // if the page is clicked anywhere except within the daterangerpicker/button
  948. // itself then call this.hide()
  949. if (
  950. // ie modal dialog fix
  951. e.type == "focusin" ||
  952. target.closest(this.element).length ||
  953. target.closest(this.container).length ||
  954. target.closest('.calendar-table').length
  955. ) return;
  956. this.hide();
  957. this.element.trigger('outsideClick.daterangepicker', this);
  958. },
  959. showCalendars: function() {
  960. this.container.addClass('show-calendar');
  961. this.move();
  962. this.element.trigger('showCalendar.daterangepicker', this);
  963. },
  964. hideCalendars: function() {
  965. this.container.removeClass('show-calendar');
  966. this.element.trigger('hideCalendar.daterangepicker', this);
  967. },
  968. clickRange: function(e) {
  969. var label = e.target.getAttribute('data-range-key');
  970. this.chosenLabel = label;
  971. if (label == this.locale.customRangeLabel) {
  972. this.showCalendars();
  973. } else {
  974. var dates = this.ranges[label];
  975. this.startDate = dates[0];
  976. this.endDate = dates[1];
  977. if (!this.timePicker) {
  978. this.startDate.startOf('day');
  979. this.endDate.endOf('day');
  980. }
  981. if (!this.alwaysShowCalendars)
  982. this.hideCalendars();
  983. this.clickApply();
  984. }
  985. },
  986. clickPrev: function(e) {
  987. var cal = $(e.target).parents('.drp-calendar');
  988. if (cal.hasClass('left')) {
  989. this.leftCalendar.month.subtract(1, 'month');
  990. if (this.linkedCalendars)
  991. this.rightCalendar.month.subtract(1, 'month');
  992. } else {
  993. this.rightCalendar.month.subtract(1, 'month');
  994. }
  995. this.updateCalendars();
  996. },
  997. clickNext: function(e) {
  998. var cal = $(e.target).parents('.drp-calendar');
  999. if (cal.hasClass('left')) {
  1000. this.leftCalendar.month.add(1, 'month');
  1001. } else {
  1002. this.rightCalendar.month.add(1, 'month');
  1003. if (this.linkedCalendars)
  1004. this.leftCalendar.month.add(1, 'month');
  1005. }
  1006. this.updateCalendars();
  1007. },
  1008. hoverDate: function(e) {
  1009. //ignore dates that can't be selected
  1010. if (!$(e.target).hasClass('available')) return;
  1011. var title = $(e.target).attr('data-title');
  1012. var row = title.substr(1, 1);
  1013. var col = title.substr(3, 1);
  1014. var cal = $(e.target).parents('.drp-calendar');
  1015. var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];
  1016. //highlight the dates between the start date and the date being hovered as a potential end date
  1017. var leftCalendar = this.leftCalendar;
  1018. var rightCalendar = this.rightCalendar;
  1019. var startDate = this.startDate;
  1020. if (!this.endDate) {
  1021. this.container.find('.drp-calendar tbody td').each(function(index, el) {
  1022. //skip week numbers, only look at dates
  1023. if ($(el).hasClass('week')) return;
  1024. var title = $(el).attr('data-title');
  1025. var row = title.substr(1, 1);
  1026. var col = title.substr(3, 1);
  1027. var cal = $(el).parents('.drp-calendar');
  1028. var dt = cal.hasClass('left') ? leftCalendar.calendar[row][col] : rightCalendar.calendar[row][col];
  1029. if ((dt.isAfter(startDate) && dt.isBefore(date)) || dt.isSame(date, 'day')) {
  1030. $(el).addClass('in-range');
  1031. } else {
  1032. $(el).removeClass('in-range');
  1033. }
  1034. });
  1035. }
  1036. },
  1037. clickDate: function(e) {
  1038. if (!$(e.target).hasClass('available')) return;
  1039. var title = $(e.target).attr('data-title');
  1040. var row = title.substr(1, 1);
  1041. var col = title.substr(3, 1);
  1042. var cal = $(e.target).parents('.drp-calendar');
  1043. var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];
  1044. //
  1045. // this function needs to do a few things:
  1046. // * alternate between selecting a start and end date for the range,
  1047. // * if the time picker is enabled, apply the hour/minute/second from the select boxes to the clicked date
  1048. // * if autoapply is enabled, and an end date was chosen, apply the selection
  1049. // * if single date picker mode, and time picker isn't enabled, apply the selection immediately
  1050. // * if one of the inputs above the calendars was focused, cancel that manual input
  1051. //
  1052. if (this.endDate || date.isBefore(this.startDate, 'day')) { //picking start
  1053. if (this.timePicker) {
  1054. var hour = parseInt(this.container.find('.left .hourselect').val(), 10);
  1055. if (!this.timePicker24Hour) {
  1056. var ampm = this.container.find('.left .ampmselect').val();
  1057. if (ampm === 'PM' && hour < 12)
  1058. hour += 12;
  1059. if (ampm === 'AM' && hour === 12)
  1060. hour = 0;
  1061. }
  1062. var minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
  1063. if (isNaN(minute)) {
  1064. minute = parseInt(this.container.find('.left .minuteselect option:last').val(), 10);
  1065. }
  1066. var second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
  1067. date = date.clone().hour(hour).minute(minute).second(second);
  1068. }
  1069. this.endDate = null;
  1070. this.setStartDate(date.clone());
  1071. } else if (!this.endDate && date.isBefore(this.startDate)) {
  1072. //special case: clicking the same date for start/end,
  1073. //but the time of the end date is before the start date
  1074. this.setEndDate(this.startDate.clone());
  1075. } else { // picking end
  1076. if (this.timePicker) {
  1077. var hour = parseInt(this.container.find('.right .hourselect').val(), 10);
  1078. if (!this.timePicker24Hour) {
  1079. var ampm = this.container.find('.right .ampmselect').val();
  1080. if (ampm === 'PM' && hour < 12)
  1081. hour += 12;
  1082. if (ampm === 'AM' && hour === 12)
  1083. hour = 0;
  1084. }
  1085. var minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
  1086. if (isNaN(minute)) {
  1087. minute = parseInt(this.container.find('.right .minuteselect option:last').val(), 10);
  1088. }
  1089. var second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
  1090. date = date.clone().hour(hour).minute(minute).second(second);
  1091. }
  1092. this.setEndDate(date.clone());
  1093. if (this.autoApply) {
  1094. this.calculateChosenLabel();
  1095. this.clickApply();
  1096. }
  1097. }
  1098. if (this.singleDatePicker) {
  1099. this.setEndDate(this.startDate);
  1100. if (!this.timePicker && this.autoApply)
  1101. this.clickApply();
  1102. }
  1103. this.updateView();
  1104. //This is to cancel the blur event handler if the mouse was in one of the inputs
  1105. e.stopPropagation();
  1106. },
  1107. calculateChosenLabel: function () {
  1108. var customRange = true;
  1109. var i = 0;
  1110. for (var range in this.ranges) {
  1111. if (this.timePicker) {
  1112. var format = this.timePickerSeconds ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD HH:mm";
  1113. //ignore times when comparing dates if time picker seconds is not enabled
  1114. if (this.startDate.format(format) == this.ranges[range][0].format(format) && this.endDate.format(format) == this.ranges[range][1].format(format)) {
  1115. customRange = false;
  1116. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').attr('data-range-key');
  1117. break;
  1118. }
  1119. } else {
  1120. //ignore times when comparing dates if time picker is not enabled
  1121. if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) {
  1122. customRange = false;
  1123. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').attr('data-range-key');
  1124. break;
  1125. }
  1126. }
  1127. i++;
  1128. }
  1129. if (customRange) {
  1130. if (this.showCustomRangeLabel) {
  1131. this.chosenLabel = this.container.find('.ranges li:last').addClass('active').attr('data-range-key');
  1132. } else {
  1133. this.chosenLabel = null;
  1134. }
  1135. this.showCalendars();
  1136. }
  1137. },
  1138. clickApply: function(e) {
  1139. this.hide();
  1140. this.element.trigger('apply.daterangepicker', this);
  1141. },
  1142. clickCancel: function(e) {
  1143. this.startDate = this.oldStartDate;
  1144. this.endDate = this.oldEndDate;
  1145. this.hide();
  1146. this.element.trigger('cancel.daterangepicker', this);
  1147. },
  1148. monthOrYearChanged: function(e) {
  1149. var isLeft = $(e.target).closest('.drp-calendar').hasClass('left'),
  1150. leftOrRight = isLeft ? 'left' : 'right',
  1151. cal = this.container.find('.drp-calendar.'+leftOrRight);
  1152. // Month must be Number for new moment versions
  1153. var month = parseInt(cal.find('.monthselect').val(), 10);
  1154. var year = cal.find('.yearselect').val();
  1155. if (!isLeft) {
  1156. if (year < this.startDate.year() || (year == this.startDate.year() && month < this.startDate.month())) {
  1157. month = this.startDate.month();
  1158. year = this.startDate.year();
  1159. }
  1160. }
  1161. if (this.minDate) {
  1162. if (year < this.minDate.year() || (year == this.minDate.year() && month < this.minDate.month())) {
  1163. month = this.minDate.month();
  1164. year = this.minDate.year();
  1165. }
  1166. }
  1167. if (this.maxDate) {
  1168. if (year > this.maxDate.year() || (year == this.maxDate.year() && month > this.maxDate.month())) {
  1169. month = this.maxDate.month();
  1170. year = this.maxDate.year();
  1171. }
  1172. }
  1173. if (isLeft) {
  1174. this.leftCalendar.month.month(month).year(year);
  1175. if (this.linkedCalendars)
  1176. this.rightCalendar.month = this.leftCalendar.month.clone().add(1, 'month');
  1177. } else {
  1178. this.rightCalendar.month.month(month).year(year);
  1179. if (this.linkedCalendars)
  1180. this.leftCalendar.month = this.rightCalendar.month.clone().subtract(1, 'month');
  1181. }
  1182. this.updateCalendars();
  1183. },
  1184. timeChanged: function(e) {
  1185. var cal = $(e.target).closest('.drp-calendar'),
  1186. isLeft = cal.hasClass('left');
  1187. var hour = parseInt(cal.find('.hourselect').val(), 10);
  1188. var minute = parseInt(cal.find('.minuteselect').val(), 10);
  1189. if (isNaN(minute)) {
  1190. minute = parseInt(cal.find('.minuteselect option:last').val(), 10);
  1191. }
  1192. var second = this.timePickerSeconds ? parseInt(cal.find('.secondselect').val(), 10) : 0;
  1193. if (!this.timePicker24Hour) {
  1194. var ampm = cal.find('.ampmselect').val();
  1195. if (ampm === 'PM' && hour < 12)
  1196. hour += 12;
  1197. if (ampm === 'AM' && hour === 12)
  1198. hour = 0;
  1199. }
  1200. if (isLeft) {
  1201. var start = this.startDate.clone();
  1202. start.hour(hour);
  1203. start.minute(minute);
  1204. start.second(second);
  1205. this.setStartDate(start);
  1206. if (this.singleDatePicker) {
  1207. this.endDate = this.startDate.clone();
  1208. } else if (this.endDate && this.endDate.format('YYYY-MM-DD') == start.format('YYYY-MM-DD') && this.endDate.isBefore(start)) {
  1209. this.setEndDate(start.clone());
  1210. }
  1211. } else if (this.endDate) {
  1212. var end = this.endDate.clone();
  1213. end.hour(hour);
  1214. end.minute(minute);
  1215. end.second(second);
  1216. this.setEndDate(end);
  1217. }
  1218. //update the calendars so all clickable dates reflect the new time component
  1219. this.updateCalendars();
  1220. //update the form inputs above the calendars with the new time
  1221. this.updateFormInputs();
  1222. //re-render the time pickers because changing one selection can affect what's enabled in another
  1223. this.renderTimePicker('left');
  1224. this.renderTimePicker('right');
  1225. },
  1226. elementChanged: function() {
  1227. if (!this.element.is('input')) return;
  1228. if (!this.element.val().length) return;
  1229. var dateString = this.element.val().split(this.locale.separator),
  1230. start = null,
  1231. end = null;
  1232. if (dateString.length === 2) {
  1233. start = moment(dateString[0], this.locale.format);
  1234. end = moment(dateString[1], this.locale.format);
  1235. }
  1236. if (this.singleDatePicker || start === null || end === null) {
  1237. start = moment(this.element.val(), this.locale.format);
  1238. end = start;
  1239. }
  1240. if (!start.isValid() || !end.isValid()) return;
  1241. this.setStartDate(start);
  1242. this.setEndDate(end);
  1243. this.updateView();
  1244. },
  1245. keydown: function(e) {
  1246. //hide on tab or enter
  1247. if ((e.keyCode === 9) || (e.keyCode === 13)) {
  1248. this.hide();
  1249. }
  1250. //hide on esc and prevent propagation
  1251. if (e.keyCode === 27) {
  1252. e.preventDefault();
  1253. e.stopPropagation();
  1254. this.hide();
  1255. }
  1256. },
  1257. updateElement: function() {
  1258. if (this.element.is('input') && this.autoUpdateInput) {
  1259. var newValue = this.startDate.format(this.locale.format);
  1260. if (!this.singleDatePicker) {
  1261. newValue += this.locale.separator + this.endDate.format(this.locale.format);
  1262. }
  1263. if (newValue !== this.element.val()) {
  1264. this.element.val(newValue).trigger('change');
  1265. }
  1266. }
  1267. },
  1268. remove: function() {
  1269. this.container.remove();
  1270. this.element.off('.daterangepicker');
  1271. this.element.removeData();
  1272. }
  1273. };
  1274. $.fn.daterangepicker = function(options, callback) {
  1275. var implementOptions = $.extend(true, {}, $.fn.daterangepicker.defaultOptions, options);
  1276. this.each(function() {
  1277. var el = $(this);
  1278. if (el.data('daterangepicker'))
  1279. el.data('daterangepicker').remove();
  1280. el.data('daterangepicker', new DateRangePicker(el, implementOptions, callback));
  1281. });
  1282. return this;
  1283. };
  1284. return DateRangePicker;
  1285. }));