daterangepicker.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. /**
  2. * @version: 1.3.9
  3. * @author: Dan Grossman http://www.dangrossman.info/
  4. * @date: 2014-07-23
  5. * @copyright: Copyright (c) 2012-2014 Dan Grossman. All rights reserved.
  6. * @license: Licensed under Apache License v2.0. See http://www.apache.org/licenses/LICENSE-2.0
  7. * @website: http://www.improvely.com/
  8. */
  9. (function(root, factory) {
  10. if (typeof define === 'function' && define.amd) {
  11. define(['moment', 'jquery', 'exports'], function(momentjs, $, exports) {
  12. root.daterangepicker = factory(root, exports, momentjs, $);
  13. });
  14. } else if (typeof exports !== 'undefined') {
  15. var momentjs = require('moment');
  16. var jQuery;
  17. try {
  18. jQuery = require('jquery');
  19. } catch (err) {
  20. jQuery = window.jQuery;
  21. if (!jQuery) throw new Error('jQuery dependency not found');
  22. }
  23. factory(root, exports, momentjs, jQuery);
  24. // Finally, as a browser global.
  25. } else {
  26. root.daterangepicker = factory(root, {}, root.momentjs, (root.jQuery || root.Zepto || root.ender || root.$));
  27. }
  28. }(this, function(root, daterangepicker, momentjs, $) {
  29. var DateRangePicker = function (element, options, cb) {
  30. // by default, the daterangepicker element is placed at the bottom of HTML body
  31. this.parentEl = 'body';
  32. //element that triggered the date range picker
  33. this.element = $(element);
  34. //tracks visible state
  35. this.isShowing = false;
  36. //create the picker HTML object
  37. var DRPTemplate = '<div class="daterangepicker dropdown-menu">' +
  38. '<div class="calendar left"></div>' +
  39. '<div class="calendar right"></div>' +
  40. '<div class="ranges">' +
  41. '<div class="range_inputs">' +
  42. '<div class="daterangepicker_start_input">' +
  43. '<label for="daterangepicker_start"></label>' +
  44. '<input class="input-mini" type="text" name="daterangepicker_start" value="" />' +
  45. '</div>' +
  46. '<div class="daterangepicker_end_input">' +
  47. '<label for="daterangepicker_end"></label>' +
  48. '<input class="input-mini" type="text" name="daterangepicker_end" value="" />' +
  49. '</div>' +
  50. '<button class="applyBtn" disabled="disabled"></button>&nbsp;' +
  51. '<button class="cancelBtn"></button>' +
  52. '</div>' +
  53. '</div>' +
  54. '</div>';
  55. //custom options
  56. if (typeof options !== 'object' || options === null)
  57. options = {};
  58. this.parentEl = (typeof options === 'object' && options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl);
  59. this.container = $(DRPTemplate).appendTo(this.parentEl);
  60. this.setOptions(options, cb);
  61. //apply CSS classes and labels to buttons
  62. var c = this.container;
  63. $.each(this.buttonClasses, function (idx, val) {
  64. c.find('button').addClass(val);
  65. });
  66. this.container.find('.daterangepicker_start_input label').html(this.locale.fromLabel);
  67. this.container.find('.daterangepicker_end_input label').html(this.locale.toLabel);
  68. if (this.applyClass.length)
  69. this.container.find('.applyBtn').addClass(this.applyClass);
  70. if (this.cancelClass.length)
  71. this.container.find('.cancelBtn').addClass(this.cancelClass);
  72. this.container.find('.applyBtn').html(this.locale.applyLabel);
  73. this.container.find('.cancelBtn').html(this.locale.cancelLabel);
  74. //event listeners
  75. this.container.find('.calendar')
  76. .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this))
  77. .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this))
  78. .on('click.daterangepicker', 'td.available', $.proxy(this.clickDate, this))
  79. .on('mouseenter.daterangepicker', 'td.available', $.proxy(this.hoverDate, this))
  80. .on('mouseleave.daterangepicker', 'td.available', $.proxy(this.updateFormInputs, this))
  81. .on('change.daterangepicker', 'select.yearselect', $.proxy(this.updateMonthYear, this))
  82. .on('change.daterangepicker', 'select.monthselect', $.proxy(this.updateMonthYear, this))
  83. .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.ampmselect', $.proxy(this.updateTime, this));
  84. this.container.find('.ranges')
  85. .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this))
  86. .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this))
  87. .on('click.daterangepicker', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.showCalendars, this))
  88. .on('change.daterangepicker', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.inputsChanged, this))
  89. .on('keydown.daterangepicker', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.inputsKeydown, this))
  90. .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this))
  91. .on('mouseenter.daterangepicker', 'li', $.proxy(this.enterRange, this))
  92. .on('mouseleave.daterangepicker', 'li', $.proxy(this.updateFormInputs, this));
  93. if (this.element.is('input')) {
  94. this.element.on({
  95. 'click.daterangepicker': $.proxy(this.show, this),
  96. 'focus.daterangepicker': $.proxy(this.show, this),
  97. 'keyup.daterangepicker': $.proxy(this.updateFromControl, this)
  98. });
  99. } else {
  100. this.element.on('click.daterangepicker', $.proxy(this.toggle, this));
  101. }
  102. };
  103. DateRangePicker.prototype = {
  104. constructor: DateRangePicker,
  105. setOptions: function(options, callback) {
  106. this.startDate = moment().startOf('day');
  107. this.endDate = moment().endOf('day');
  108. this.minDate = false;
  109. this.maxDate = false;
  110. this.dateLimit = false;
  111. this.showDropdowns = false;
  112. this.showWeekNumbers = false;
  113. this.timePicker = false;
  114. this.timePickerIncrement = 30;
  115. this.timePicker12Hour = true;
  116. this.singleDatePicker = false;
  117. this.ranges = {};
  118. this.opens = 'right';
  119. if (this.element.hasClass('pull-right'))
  120. this.opens = 'left';
  121. this.buttonClasses = ['btn', 'btn-small btn-sm'];
  122. this.applyClass = 'btn-success';
  123. this.cancelClass = 'btn-default';
  124. this.format = 'MM/DD/YYYY';
  125. this.separator = ' - ';
  126. this.locale = {
  127. applyLabel: 'Apply',
  128. cancelLabel: 'Cancel',
  129. fromLabel: 'From',
  130. toLabel: 'To',
  131. weekLabel: 'W',
  132. customRangeLabel: 'Custom Range',
  133. daysOfWeek: moment()._lang._weekdaysMin.slice(),
  134. monthNames: moment()._lang._monthsShort.slice(),
  135. firstDay: moment()._lang._week.dow
  136. };
  137. this.cb = function () { };
  138. if (typeof options.format === 'string')
  139. this.format = options.format;
  140. if (typeof options.separator === 'string')
  141. this.separator = options.separator;
  142. if (typeof options.startDate === 'string')
  143. this.startDate = moment(options.startDate, this.format);
  144. if (typeof options.endDate === 'string')
  145. this.endDate = moment(options.endDate, this.format);
  146. if (typeof options.minDate === 'string')
  147. this.minDate = moment(options.minDate, this.format);
  148. if (typeof options.maxDate === 'string')
  149. this.maxDate = moment(options.maxDate, this.format);
  150. if (typeof options.startDate === 'object')
  151. this.startDate = moment(options.startDate);
  152. if (typeof options.endDate === 'object')
  153. this.endDate = moment(options.endDate);
  154. if (typeof options.minDate === 'object')
  155. this.minDate = moment(options.minDate);
  156. if (typeof options.maxDate === 'object')
  157. this.maxDate = moment(options.maxDate);
  158. if (typeof options.applyClass === 'string')
  159. this.applyClass = options.applyClass;
  160. if (typeof options.cancelClass === 'string')
  161. this.cancelClass = options.cancelClass;
  162. if (typeof options.dateLimit === 'object')
  163. this.dateLimit = options.dateLimit;
  164. if (typeof options.locale === 'object') {
  165. if (typeof options.locale.daysOfWeek === 'object') {
  166. // Create a copy of daysOfWeek to avoid modification of original
  167. // options object for reusability in multiple daterangepicker instances
  168. this.locale.daysOfWeek = options.locale.daysOfWeek.slice();
  169. }
  170. if (typeof options.locale.monthNames === 'object') {
  171. this.locale.monthNames = options.locale.monthNames.slice();
  172. }
  173. if (typeof options.locale.firstDay === 'number') {
  174. this.locale.firstDay = options.locale.firstDay;
  175. }
  176. if (typeof options.locale.applyLabel === 'string') {
  177. this.locale.applyLabel = options.locale.applyLabel;
  178. }
  179. if (typeof options.locale.cancelLabel === 'string') {
  180. this.locale.cancelLabel = options.locale.cancelLabel;
  181. }
  182. if (typeof options.locale.fromLabel === 'string') {
  183. this.locale.fromLabel = options.locale.fromLabel;
  184. }
  185. if (typeof options.locale.toLabel === 'string') {
  186. this.locale.toLabel = options.locale.toLabel;
  187. }
  188. if (typeof options.locale.weekLabel === 'string') {
  189. this.locale.weekLabel = options.locale.weekLabel;
  190. }
  191. if (typeof options.locale.customRangeLabel === 'string') {
  192. this.locale.customRangeLabel = options.locale.customRangeLabel;
  193. }
  194. }
  195. if (typeof options.opens === 'string')
  196. this.opens = options.opens;
  197. if (typeof options.showWeekNumbers === 'boolean') {
  198. this.showWeekNumbers = options.showWeekNumbers;
  199. }
  200. if (typeof options.buttonClasses === 'string') {
  201. this.buttonClasses = [options.buttonClasses];
  202. }
  203. if (typeof options.buttonClasses === 'object') {
  204. this.buttonClasses = options.buttonClasses;
  205. }
  206. if (typeof options.showDropdowns === 'boolean') {
  207. this.showDropdowns = options.showDropdowns;
  208. }
  209. if (typeof options.singleDatePicker === 'boolean') {
  210. this.singleDatePicker = options.singleDatePicker;
  211. }
  212. if (typeof options.timePicker === 'boolean') {
  213. this.timePicker = options.timePicker;
  214. }
  215. if (typeof options.timePickerIncrement === 'number') {
  216. this.timePickerIncrement = options.timePickerIncrement;
  217. }
  218. if (typeof options.timePicker12Hour === 'boolean') {
  219. this.timePicker12Hour = options.timePicker12Hour;
  220. }
  221. // update day names order to firstDay
  222. if (this.locale.firstDay != 0) {
  223. var iterator = this.locale.firstDay;
  224. while (iterator > 0) {
  225. this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
  226. iterator--;
  227. }
  228. }
  229. var start, end, range;
  230. //if no start/end dates set, check if an input element contains initial values
  231. if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
  232. if ($(this.element).is('input[type=text]')) {
  233. var val = $(this.element).val();
  234. var split = val.split(this.separator);
  235. start = end = null;
  236. if (split.length == 2) {
  237. start = moment(split[0], this.format);
  238. end = moment(split[1], this.format);
  239. } else if (this.singleDatePicker) {
  240. start = moment(val, this.format);
  241. end = moment(val, this.format);
  242. }
  243. if (start !== null && end !== null) {
  244. this.startDate = start;
  245. this.endDate = end;
  246. }
  247. }
  248. }
  249. if (typeof options.ranges === 'object') {
  250. for (range in options.ranges) {
  251. start = moment(options.ranges[range][0]);
  252. end = moment(options.ranges[range][1]);
  253. // If we have a min/max date set, bound this range
  254. // to it, but only if it would otherwise fall
  255. // outside of the min/max.
  256. if (this.minDate && start.isBefore(this.minDate))
  257. start = moment(this.minDate);
  258. if (this.maxDate && end.isAfter(this.maxDate))
  259. end = moment(this.maxDate);
  260. // If the end of the range is before the minimum (if min is set) OR
  261. // the start of the range is after the max (also if set) don't display this
  262. // range option.
  263. if ((this.minDate && end.isBefore(this.minDate)) || (this.maxDate && start.isAfter(this.maxDate))) {
  264. continue;
  265. }
  266. this.ranges[range] = [start, end];
  267. }
  268. var list = '<ul>';
  269. for (range in this.ranges) {
  270. list += '<li>' + range + '</li>';
  271. }
  272. list += '<li>' + this.locale.customRangeLabel + '</li>';
  273. list += '</ul>';
  274. this.container.find('.ranges ul').remove();
  275. this.container.find('.ranges').prepend(list);
  276. }
  277. if (typeof callback === 'function') {
  278. this.cb = callback;
  279. }
  280. if (!this.timePicker) {
  281. this.startDate = this.startDate.startOf('day');
  282. this.endDate = this.endDate.endOf('day');
  283. }
  284. if (this.singleDatePicker) {
  285. this.opens = 'right';
  286. this.container.find('.calendar.right').show();
  287. this.container.find('.calendar.left').hide();
  288. this.container.find('.ranges').hide();
  289. if (!this.container.find('.calendar.right').hasClass('single'))
  290. this.container.find('.calendar.right').addClass('single');
  291. } else {
  292. this.container.find('.calendar.right').removeClass('single');
  293. this.container.find('.ranges').show();
  294. }
  295. this.oldStartDate = this.startDate.clone();
  296. this.oldEndDate = this.endDate.clone();
  297. this.oldChosenLabel = this.chosenLabel;
  298. this.leftCalendar = {
  299. month: moment([this.startDate.year(), this.startDate.month(), 1, this.startDate.hour(), this.startDate.minute()]),
  300. calendar: []
  301. };
  302. this.rightCalendar = {
  303. month: moment([this.endDate.year(), this.endDate.month(), 1, this.endDate.hour(), this.endDate.minute()]),
  304. calendar: []
  305. };
  306. if (this.opens == 'right') {
  307. //swap calendar positions
  308. var left = this.container.find('.calendar.left');
  309. var right = this.container.find('.calendar.right');
  310. left.removeClass('left').addClass('right');
  311. right.removeClass('right').addClass('left');
  312. }
  313. if (typeof options.ranges === 'undefined' && !this.singleDatePicker) {
  314. this.container.addClass('show-calendar');
  315. }
  316. this.container.addClass('opens' + this.opens);
  317. this.updateView();
  318. this.updateCalendars();
  319. },
  320. setStartDate: function(startDate) {
  321. if (typeof startDate === 'string')
  322. this.startDate = moment(startDate, this.format);
  323. if (typeof startDate === 'object')
  324. this.startDate = moment(startDate);
  325. if (!this.timePicker)
  326. this.startDate = this.startDate.startOf('day');
  327. this.oldStartDate = this.startDate.clone();
  328. this.updateView();
  329. this.updateCalendars();
  330. this.updateInputText();
  331. },
  332. setEndDate: function(endDate) {
  333. if (typeof endDate === 'string')
  334. this.endDate = moment(endDate, this.format);
  335. if (typeof endDate === 'object')
  336. this.endDate = moment(endDate);
  337. if (!this.timePicker)
  338. this.endDate = this.endDate.endOf('day');
  339. this.oldEndDate = this.endDate.clone();
  340. this.updateView();
  341. this.updateCalendars();
  342. this.updateInputText();
  343. },
  344. updateView: function () {
  345. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
  346. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
  347. this.updateFormInputs();
  348. },
  349. updateFormInputs: function () {
  350. this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.format));
  351. this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.format));
  352. if (this.startDate.isSame(this.endDate) || this.startDate.isBefore(this.endDate)) {
  353. this.container.find('button.applyBtn').removeAttr('disabled');
  354. } else {
  355. this.container.find('button.applyBtn').attr('disabled', 'disabled');
  356. }
  357. },
  358. updateFromControl: function () {
  359. if (!this.element.is('input')) return;
  360. if (!this.element.val().length) return;
  361. var dateString = this.element.val().split(this.separator),
  362. start = null,
  363. end = null;
  364. if(dateString.length === 2) {
  365. start = moment(dateString[0], this.format);
  366. end = moment(dateString[1], this.format);
  367. }
  368. if (this.singleDatePicker || start === null || end === null) {
  369. start = moment(this.element.val(), this.format);
  370. end = start;
  371. }
  372. if (end.isBefore(start)) return;
  373. this.oldStartDate = this.startDate.clone();
  374. this.oldEndDate = this.endDate.clone();
  375. this.startDate = start;
  376. this.endDate = end;
  377. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  378. this.notify();
  379. this.updateCalendars();
  380. },
  381. notify: function () {
  382. this.updateView();
  383. this.cb(this.startDate, this.endDate, this.chosenLabel);
  384. },
  385. move: function () {
  386. var parentOffset = { top: 0, left: 0 };
  387. if (!this.parentEl.is('body')) {
  388. parentOffset = {
  389. top: this.parentEl.offset().top - this.parentEl.scrollTop(),
  390. left: this.parentEl.offset().left - this.parentEl.scrollLeft()
  391. };
  392. }
  393. if (this.opens == 'left') {
  394. this.container.css({
  395. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  396. right: $(window).width() - this.element.offset().left - this.element.outerWidth() - parentOffset.left,
  397. left: 'auto'
  398. });
  399. if (this.container.offset().left < 0) {
  400. this.container.css({
  401. right: 'auto',
  402. left: 9
  403. });
  404. }
  405. } else {
  406. this.container.css({
  407. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  408. left: this.element.offset().left - parentOffset.left,
  409. right: 'auto'
  410. });
  411. if (this.container.offset().left + this.container.outerWidth() > $(window).width()) {
  412. this.container.css({
  413. left: 'auto',
  414. right: 0
  415. });
  416. }
  417. }
  418. },
  419. toggle: function (e) {
  420. if (this.element.hasClass('active')) {
  421. this.hide();
  422. } else {
  423. this.show();
  424. }
  425. },
  426. show: function (e) {
  427. if (this.isShowing) return;
  428. this.element.addClass('active');
  429. this.container.show();
  430. this.move();
  431. // Create a click proxy that is private to this instance of datepicker, for unbinding
  432. this._outsideClickProxy = $.proxy(function (e) { this.outsideClick(e); }, this);
  433. // Bind global datepicker mousedown for hiding and
  434. $(document)
  435. .on('mousedown.daterangepicker', this._outsideClickProxy)
  436. // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
  437. .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
  438. // and also close when focus changes to outside the picker (eg. tabbing between controls)
  439. .on('focusin.daterangepicker', this._outsideClickProxy);
  440. this.isShowing = true;
  441. this.element.trigger('show.daterangepicker', this);
  442. },
  443. outsideClick: function (e) {
  444. var target = $(e.target);
  445. // if the page is clicked anywhere except within the daterangerpicker/button
  446. // itself then call this.hide()
  447. if (
  448. target.closest(this.element).length ||
  449. target.closest(this.container).length ||
  450. target.closest('.calendar-date').length
  451. ) return;
  452. this.hide();
  453. },
  454. hide: function (e) {
  455. if (!this.isShowing) return;
  456. $(document)
  457. .off('mousedown.daterangepicker')
  458. .off('click.daterangepicker', '[data-toggle=dropdown]')
  459. .off('focusin.daterangepicker');
  460. this.element.removeClass('active');
  461. this.container.hide();
  462. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  463. this.notify();
  464. this.oldStartDate = this.startDate.clone();
  465. this.oldEndDate = this.endDate.clone();
  466. this.isShowing = false;
  467. this.element.trigger('hide.daterangepicker', this);
  468. },
  469. enterRange: function (e) {
  470. // mouse pointer has entered a range label
  471. var label = e.target.innerHTML;
  472. if (label == this.locale.customRangeLabel) {
  473. this.updateView();
  474. } else {
  475. var dates = this.ranges[label];
  476. this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.format));
  477. this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.format));
  478. }
  479. },
  480. showCalendars: function() {
  481. this.container.addClass('show-calendar');
  482. this.move();
  483. this.element.trigger('showCalendar.daterangepicker', this);
  484. },
  485. hideCalendars: function() {
  486. this.container.removeClass('show-calendar');
  487. this.element.trigger('hideCalendar.daterangepicker', this);
  488. },
  489. // when a date is typed into the start to end date textboxes
  490. inputsChanged: function (e) {
  491. var el = $(e.target);
  492. var date = moment(el.val());
  493. if (!date.isValid()) return;
  494. var startDate, endDate;
  495. if (el.attr('name') === 'daterangepicker_start') {
  496. startDate = date;
  497. endDate = this.endDate;
  498. } else {
  499. startDate = this.startDate;
  500. endDate = date;
  501. }
  502. this.setCustomDates(startDate, endDate);
  503. },
  504. inputsKeydown: function(e) {
  505. if (e.keyCode === 13) {
  506. this.inputsChanged(e);
  507. this.notify();
  508. }
  509. },
  510. updateInputText: function() {
  511. if (this.element.is('input') && !this.singleDatePicker) {
  512. this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
  513. } else if (this.element.is('input')) {
  514. this.element.val(this.startDate.format(this.format));
  515. }
  516. },
  517. clickRange: function (e) {
  518. var label = e.target.innerHTML;
  519. this.chosenLabel = label;
  520. if (label == this.locale.customRangeLabel) {
  521. this.showCalendars();
  522. } else {
  523. var dates = this.ranges[label];
  524. this.startDate = dates[0];
  525. this.endDate = dates[1];
  526. if (!this.timePicker) {
  527. this.startDate.startOf('day');
  528. this.endDate.endOf('day');
  529. }
  530. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
  531. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
  532. this.updateCalendars();
  533. this.updateInputText();
  534. this.hideCalendars();
  535. this.hide();
  536. this.element.trigger('apply.daterangepicker', this);
  537. }
  538. },
  539. clickPrev: function (e) {
  540. var cal = $(e.target).parents('.calendar');
  541. if (cal.hasClass('left')) {
  542. this.leftCalendar.month.subtract('month', 1);
  543. } else {
  544. this.rightCalendar.month.subtract('month', 1);
  545. }
  546. this.updateCalendars();
  547. },
  548. clickNext: function (e) {
  549. var cal = $(e.target).parents('.calendar');
  550. if (cal.hasClass('left')) {
  551. this.leftCalendar.month.add('month', 1);
  552. } else {
  553. this.rightCalendar.month.add('month', 1);
  554. }
  555. this.updateCalendars();
  556. },
  557. hoverDate: function (e) {
  558. var title = $(e.target).attr('data-title');
  559. var row = title.substr(1, 1);
  560. var col = title.substr(3, 1);
  561. var cal = $(e.target).parents('.calendar');
  562. if (cal.hasClass('left')) {
  563. this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].format(this.format));
  564. } else {
  565. this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].format(this.format));
  566. }
  567. },
  568. setCustomDates: function(startDate, endDate) {
  569. this.chosenLabel = this.locale.customRangeLabel;
  570. if (startDate.isAfter(endDate)) {
  571. var difference = this.endDate.diff(this.startDate);
  572. endDate = moment(startDate).add('ms', difference);
  573. }
  574. this.startDate = startDate;
  575. this.endDate = endDate;
  576. this.updateView();
  577. this.updateCalendars();
  578. },
  579. clickDate: function (e) {
  580. var title = $(e.target).attr('data-title');
  581. var row = title.substr(1, 1);
  582. var col = title.substr(3, 1);
  583. var cal = $(e.target).parents('.calendar');
  584. var startDate, endDate;
  585. if (cal.hasClass('left')) {
  586. startDate = this.leftCalendar.calendar[row][col];
  587. endDate = this.endDate;
  588. if (typeof this.dateLimit === 'object') {
  589. var maxDate = moment(startDate).add(this.dateLimit).startOf('day');
  590. if (endDate.isAfter(maxDate)) {
  591. endDate = maxDate;
  592. }
  593. }
  594. } else {
  595. startDate = this.startDate;
  596. endDate = this.rightCalendar.calendar[row][col];
  597. if (typeof this.dateLimit === 'object') {
  598. var minDate = moment(endDate).subtract(this.dateLimit).startOf('day');
  599. if (startDate.isBefore(minDate)) {
  600. startDate = minDate;
  601. }
  602. }
  603. }
  604. if (this.singleDatePicker && cal.hasClass('left')) {
  605. endDate = startDate.clone();
  606. } else if (this.singleDatePicker && cal.hasClass('right')) {
  607. startDate = endDate.clone();
  608. }
  609. cal.find('td').removeClass('active');
  610. $(e.target).addClass('active');
  611. this.setCustomDates(startDate, endDate);
  612. if (!this.timePicker)
  613. endDate.endOf('day');
  614. if (this.singleDatePicker)
  615. this.clickApply();
  616. },
  617. clickApply: function (e) {
  618. this.updateInputText();
  619. this.hide();
  620. this.element.trigger('apply.daterangepicker', this);
  621. },
  622. clickCancel: function (e) {
  623. this.startDate = this.oldStartDate;
  624. this.endDate = this.oldEndDate;
  625. this.chosenLabel = this.oldChosenLabel;
  626. this.updateView();
  627. this.updateCalendars();
  628. this.hide();
  629. this.element.trigger('cancel.daterangepicker', this);
  630. },
  631. updateMonthYear: function (e) {
  632. var isLeft = $(e.target).closest('.calendar').hasClass('left'),
  633. leftOrRight = isLeft ? 'left' : 'right',
  634. cal = this.container.find('.calendar.'+leftOrRight);
  635. // Month must be Number for new moment versions
  636. var month = parseInt(cal.find('.monthselect').val(), 10);
  637. var year = cal.find('.yearselect').val();
  638. this[leftOrRight+'Calendar'].month.month(month).year(year);
  639. this.updateCalendars();
  640. },
  641. updateTime: function(e) {
  642. var cal = $(e.target).closest('.calendar'),
  643. isLeft = cal.hasClass('left');
  644. var hour = parseInt(cal.find('.hourselect').val(), 10);
  645. var minute = parseInt(cal.find('.minuteselect').val(), 10);
  646. if (this.timePicker12Hour) {
  647. var ampm = cal.find('.ampmselect').val();
  648. if (ampm === 'PM' && hour < 12)
  649. hour += 12;
  650. if (ampm === 'AM' && hour === 12)
  651. hour = 0;
  652. }
  653. if (isLeft) {
  654. var start = this.startDate.clone();
  655. start.hour(hour);
  656. start.minute(minute);
  657. this.startDate = start;
  658. this.leftCalendar.month.hour(hour).minute(minute);
  659. } else {
  660. var end = this.endDate.clone();
  661. end.hour(hour);
  662. end.minute(minute);
  663. this.endDate = end;
  664. this.rightCalendar.month.hour(hour).minute(minute);
  665. }
  666. this.updateCalendars();
  667. },
  668. updateCalendars: function () {
  669. this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.month(), this.leftCalendar.month.year(), this.leftCalendar.month.hour(), this.leftCalendar.month.minute(), 'left');
  670. this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.month(), this.rightCalendar.month.year(), this.rightCalendar.month.hour(), this.rightCalendar.month.minute(), 'right');
  671. this.container.find('.calendar.left').empty().html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.maxDate));
  672. this.container.find('.calendar.right').empty().html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.startDate, this.maxDate));
  673. this.container.find('.ranges li').removeClass('active');
  674. var customRange = true;
  675. var i = 0;
  676. for (var range in this.ranges) {
  677. if (this.timePicker) {
  678. if (this.startDate.isSame(this.ranges[range][0]) && this.endDate.isSame(this.ranges[range][1])) {
  679. customRange = false;
  680. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')')
  681. .addClass('active').html();
  682. }
  683. } else {
  684. //ignore times when comparing dates if time picker is not enabled
  685. 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')) {
  686. customRange = false;
  687. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')')
  688. .addClass('active').html();
  689. }
  690. }
  691. i++;
  692. }
  693. if (customRange) {
  694. this.chosenLabel = this.container.find('.ranges li:last').addClass('active').html();
  695. this.showCalendars();
  696. }
  697. },
  698. buildCalendar: function (month, year, hour, minute, side) {
  699. var daysInMonth = moment([year, month]).daysInMonth();
  700. var firstDay = moment([year, month, 1]);
  701. var lastDay = moment([year, month, daysInMonth]);
  702. var lastMonth = moment(firstDay).subtract('month', 1).month();
  703. var lastYear = moment(firstDay).subtract('month', 1).year();
  704. var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
  705. var dayOfWeek = firstDay.day();
  706. var i;
  707. //initialize a 6 rows x 7 columns array for the calendar
  708. var calendar = [];
  709. calendar.firstDay = firstDay;
  710. calendar.lastDay = lastDay;
  711. for (i = 0; i < 6; i++) {
  712. calendar[i] = [];
  713. }
  714. //populate the calendar with date objects
  715. var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
  716. if (startDay > daysInLastMonth)
  717. startDay -= 7;
  718. if (dayOfWeek == this.locale.firstDay)
  719. startDay = daysInLastMonth - 6;
  720. var curDate = moment([lastYear, lastMonth, startDay, 12, minute]);
  721. var col, row;
  722. for (i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add('hour', 24)) {
  723. if (i > 0 && col % 7 === 0) {
  724. col = 0;
  725. row++;
  726. }
  727. calendar[row][col] = curDate.clone().hour(hour);
  728. curDate.hour(12);
  729. }
  730. return calendar;
  731. },
  732. renderDropdowns: function (selected, minDate, maxDate) {
  733. var currentMonth = selected.month();
  734. var monthHtml = '<select class="monthselect">';
  735. var inMinYear = false;
  736. var inMaxYear = false;
  737. for (var m = 0; m < 12; m++) {
  738. if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) {
  739. monthHtml += "<option value='" + m + "'" +
  740. (m === currentMonth ? " selected='selected'" : "") +
  741. ">" + this.locale.monthNames[m] + "</option>";
  742. }
  743. }
  744. monthHtml += "</select>";
  745. var currentYear = selected.year();
  746. var maxYear = (maxDate && maxDate.year()) || (currentYear + 5);
  747. var minYear = (minDate && minDate.year()) || (currentYear - 50);
  748. var yearHtml = '<select class="yearselect">';
  749. for (var y = minYear; y <= maxYear; y++) {
  750. yearHtml += '<option value="' + y + '"' +
  751. (y === currentYear ? ' selected="selected"' : '') +
  752. '>' + y + '</option>';
  753. }
  754. yearHtml += '</select>';
  755. return monthHtml + yearHtml;
  756. },
  757. renderCalendar: function (calendar, selected, minDate, maxDate) {
  758. var html = '<div class="calendar-date">';
  759. html += '<table class="table-condensed">';
  760. html += '<thead>';
  761. html += '<tr>';
  762. // add empty cell for week number
  763. if (this.showWeekNumbers)
  764. html += '<th></th>';
  765. if (!minDate || minDate.isBefore(calendar.firstDay)) {
  766. html += '<th class="prev available"><i class="glyph-icon icon-arrow-left icon-arrow-left glyphicon glyphicon-arrow-left"></i></th>';
  767. } else {
  768. html += '<th></th>';
  769. }
  770. var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
  771. if (this.showDropdowns) {
  772. dateHtml = this.renderDropdowns(calendar[1][1], minDate, maxDate);
  773. }
  774. html += '<th colspan="5" class="month">' + dateHtml + '</th>';
  775. if (!maxDate || maxDate.isAfter(calendar.lastDay)) {
  776. html += '<th class="next available"><i class="glyph-icon icon-arrow-right icon-arrow-right glyphicon glyphicon-arrow-right"></i></th>';
  777. } else {
  778. html += '<th></th>';
  779. }
  780. html += '</tr>';
  781. html += '<tr>';
  782. // add week number label
  783. if (this.showWeekNumbers)
  784. html += '<th class="week">' + this.locale.weekLabel + '</th>';
  785. $.each(this.locale.daysOfWeek, function (index, dayOfWeek) {
  786. html += '<th>' + dayOfWeek + '</th>';
  787. });
  788. html += '</tr>';
  789. html += '</thead>';
  790. html += '<tbody>';
  791. for (var row = 0; row < 6; row++) {
  792. html += '<tr>';
  793. // add week number
  794. if (this.showWeekNumbers)
  795. html += '<td class="week">' + calendar[row][0].week() + '</td>';
  796. for (var col = 0; col < 7; col++) {
  797. var cname = 'available ';
  798. cname += (calendar[row][col].month() == calendar[1][1].month()) ? '' : 'off';
  799. if ((minDate && calendar[row][col].isBefore(minDate, 'day')) || (maxDate && calendar[row][col].isAfter(maxDate, 'day'))) {
  800. cname = ' off disabled ';
  801. } else if (calendar[row][col].format('YYYY-MM-DD') == selected.format('YYYY-MM-DD')) {
  802. cname += ' active ';
  803. if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD')) {
  804. cname += ' start-date ';
  805. }
  806. if (calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD')) {
  807. cname += ' end-date ';
  808. }
  809. } else if (calendar[row][col] >= this.startDate && calendar[row][col] <= this.endDate) {
  810. cname += ' in-range ';
  811. if (calendar[row][col].isSame(this.startDate)) { cname += ' start-date '; }
  812. if (calendar[row][col].isSame(this.endDate)) { cname += ' end-date '; }
  813. }
  814. var title = 'r' + row + 'c' + col;
  815. html += '<td class="' + cname.replace(/\s+/g, ' ').replace(/^\s?(.*?)\s?$/, '$1') + '" data-title="' + title + '">' + calendar[row][col].date() + '</td>';
  816. }
  817. html += '</tr>';
  818. }
  819. html += '</tbody>';
  820. html += '</table>';
  821. html += '</div>';
  822. var i;
  823. if (this.timePicker) {
  824. html += '<div class="calendar-time">';
  825. html += '<select class="hourselect">';
  826. var start = 0;
  827. var end = 23;
  828. var selected_hour = selected.hour();
  829. if (this.timePicker12Hour) {
  830. start = 1;
  831. end = 12;
  832. if (selected_hour >= 12)
  833. selected_hour -= 12;
  834. if (selected_hour === 0)
  835. selected_hour = 12;
  836. }
  837. for (i = start; i <= end; i++) {
  838. if (i == selected_hour) {
  839. html += '<option value="' + i + '" selected="selected">' + i + '</option>';
  840. } else {
  841. html += '<option value="' + i + '">' + i + '</option>';
  842. }
  843. }
  844. html += '</select> : ';
  845. html += '<select class="minuteselect">';
  846. for (i = 0; i < 60; i += this.timePickerIncrement) {
  847. var num = i;
  848. if (num < 10)
  849. num = '0' + num;
  850. if (i == selected.minute()) {
  851. html += '<option value="' + i + '" selected="selected">' + num + '</option>';
  852. } else {
  853. html += '<option value="' + i + '">' + num + '</option>';
  854. }
  855. }
  856. html += '</select> ';
  857. if (this.timePicker12Hour) {
  858. html += '<select class="ampmselect">';
  859. if (selected.hour() >= 12) {
  860. html += '<option value="AM">AM</option><option value="PM" selected="selected">PM</option>';
  861. } else {
  862. html += '<option value="AM" selected="selected">AM</option><option value="PM">PM</option>';
  863. }
  864. html += '</select>';
  865. }
  866. html += '</div>';
  867. }
  868. return html;
  869. },
  870. remove: function() {
  871. this.container.remove();
  872. this.element.off('.daterangepicker');
  873. this.element.removeData('daterangepicker');
  874. }
  875. };
  876. $.fn.daterangepicker = function (options, cb) {
  877. this.each(function () {
  878. var el = $(this);
  879. if (el.data('daterangepicker'))
  880. el.data('daterangepicker').remove();
  881. el.data('daterangepicker', new DateRangePicker(el, options, cb));
  882. });
  883. return this;
  884. };
  885. }));