You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1628 lines
68 KiB

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