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.

1653 lines
69 KiB

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