daterangepicker.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. /**
  2. * @version: 1.3.13
  3. * @author: Dan Grossman http://www.dangrossman.info/
  4. * @date: 2014-09-04
  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.moment, (root.jQuery || root.Zepto || root.ender || root.$));
  27. }
  28. }(this, function(root, daterangepicker, moment, $) {
  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.weekdaysMin(),
  134. monthNames: moment.monthsShort(),
  135. firstDay: moment.localeData()._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. if (this.singleDatePicker) {
  212. this.endDate = this.startDate.clone();
  213. }
  214. }
  215. if (typeof options.timePicker === 'boolean') {
  216. this.timePicker = options.timePicker;
  217. }
  218. if (typeof options.timePickerIncrement === 'number') {
  219. this.timePickerIncrement = options.timePickerIncrement;
  220. }
  221. if (typeof options.timePicker12Hour === 'boolean') {
  222. this.timePicker12Hour = options.timePicker12Hour;
  223. }
  224. // update day names order to firstDay
  225. if (this.locale.firstDay != 0) {
  226. var iterator = this.locale.firstDay;
  227. while (iterator > 0) {
  228. this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
  229. iterator--;
  230. }
  231. }
  232. var start, end, range;
  233. //if no start/end dates set, check if an input element contains initial values
  234. if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
  235. if ($(this.element).is('input[type=text]')) {
  236. var val = $(this.element).val();
  237. var split = val.split(this.separator);
  238. start = end = null;
  239. if (split.length == 2) {
  240. start = moment(split[0], this.format);
  241. end = moment(split[1], this.format);
  242. } else if (this.singleDatePicker) {
  243. start = moment(val, this.format);
  244. end = moment(val, this.format);
  245. }
  246. if (start !== null && end !== null) {
  247. this.startDate = start;
  248. this.endDate = end;
  249. }
  250. }
  251. }
  252. if (typeof options.ranges === 'object') {
  253. for (range in options.ranges) {
  254. start = moment(options.ranges[range][0]);
  255. end = moment(options.ranges[range][1]);
  256. // If we have a min/max date set, bound this range
  257. // to it, but only if it would otherwise fall
  258. // outside of the min/max.
  259. if (this.minDate && start.isBefore(this.minDate))
  260. start = moment(this.minDate);
  261. if (this.maxDate && end.isAfter(this.maxDate))
  262. end = moment(this.maxDate);
  263. // If the end of the range is before the minimum (if min is set) OR
  264. // the start of the range is after the max (also if set) don't display this
  265. // range option.
  266. if ((this.minDate && end.isBefore(this.minDate)) || (this.maxDate && start.isAfter(this.maxDate))) {
  267. continue;
  268. }
  269. this.ranges[range] = [start, end];
  270. }
  271. var list = '<ul>';
  272. for (range in this.ranges) {
  273. list += '<li>' + range + '</li>';
  274. }
  275. list += '<li>' + this.locale.customRangeLabel + '</li>';
  276. list += '</ul>';
  277. this.container.find('.ranges ul').remove();
  278. this.container.find('.ranges').prepend(list);
  279. }
  280. if (typeof callback === 'function') {
  281. this.cb = callback;
  282. }
  283. if (!this.timePicker) {
  284. this.startDate = this.startDate.startOf('day');
  285. this.endDate = this.endDate.endOf('day');
  286. }
  287. if (this.singleDatePicker) {
  288. this.opens = 'right';
  289. this.container.addClass('single');
  290. this.container.find('.calendar.right').show();
  291. this.container.find('.calendar.left').hide();
  292. if (!this.timePicker) {
  293. this.container.find('.ranges').hide();
  294. } else {
  295. this.container.find('.ranges .daterangepicker_start_input, .ranges .daterangepicker_end_input').hide();
  296. }
  297. if (!this.container.find('.calendar.right').hasClass('single'))
  298. this.container.find('.calendar.right').addClass('single');
  299. } else {
  300. this.container.removeClass('single');
  301. this.container.find('.calendar.right').removeClass('single');
  302. this.container.find('.ranges').show();
  303. }
  304. this.oldStartDate = this.startDate.clone();
  305. this.oldEndDate = this.endDate.clone();
  306. this.oldChosenLabel = this.chosenLabel;
  307. this.leftCalendar = {
  308. month: moment([this.startDate.year(), this.startDate.month(), 1, this.startDate.hour(), this.startDate.minute()]),
  309. calendar: []
  310. };
  311. this.rightCalendar = {
  312. month: moment([this.endDate.year(), this.endDate.month(), 1, this.endDate.hour(), this.endDate.minute()]),
  313. calendar: []
  314. };
  315. if (this.opens == 'right') {
  316. //swap calendar positions
  317. var left = this.container.find('.calendar.left');
  318. var right = this.container.find('.calendar.right');
  319. if (right.hasClass('single')) {
  320. right.removeClass('single');
  321. left.addClass('single');
  322. }
  323. left.removeClass('left').addClass('right');
  324. right.removeClass('right').addClass('left');
  325. if (this.singleDatePicker) {
  326. left.show();
  327. right.hide();
  328. }
  329. }
  330. if (typeof options.ranges === 'undefined' && !this.singleDatePicker) {
  331. this.container.addClass('show-calendar');
  332. }
  333. this.container.addClass('opens' + this.opens);
  334. this.updateView();
  335. this.updateCalendars();
  336. },
  337. setStartDate: function(startDate) {
  338. if (typeof startDate === 'string')
  339. this.startDate = moment(startDate, this.format);
  340. if (typeof startDate === 'object')
  341. this.startDate = moment(startDate);
  342. if (!this.timePicker)
  343. this.startDate = this.startDate.startOf('day');
  344. this.oldStartDate = this.startDate.clone();
  345. this.updateView();
  346. this.updateCalendars();
  347. this.updateInputText();
  348. },
  349. setEndDate: function(endDate) {
  350. if (typeof endDate === 'string')
  351. this.endDate = moment(endDate, this.format);
  352. if (typeof endDate === 'object')
  353. this.endDate = moment(endDate);
  354. if (!this.timePicker)
  355. this.endDate = this.endDate.endOf('day');
  356. this.oldEndDate = this.endDate.clone();
  357. this.updateView();
  358. this.updateCalendars();
  359. this.updateInputText();
  360. },
  361. updateView: function () {
  362. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
  363. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
  364. this.updateFormInputs();
  365. },
  366. updateFormInputs: function () {
  367. this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.format));
  368. this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.format));
  369. if (this.startDate.isSame(this.endDate) || this.startDate.isBefore(this.endDate)) {
  370. this.container.find('button.applyBtn').removeAttr('disabled');
  371. } else {
  372. this.container.find('button.applyBtn').attr('disabled', 'disabled');
  373. }
  374. },
  375. updateFromControl: function () {
  376. if (!this.element.is('input')) return;
  377. if (!this.element.val().length) return;
  378. var dateString = this.element.val().split(this.separator),
  379. start = null,
  380. end = null;
  381. if(dateString.length === 2) {
  382. start = moment(dateString[0], this.format);
  383. end = moment(dateString[1], this.format);
  384. }
  385. if (this.singleDatePicker || start === null || end === null) {
  386. start = moment(this.element.val(), this.format);
  387. end = start;
  388. }
  389. if (end.isBefore(start)) return;
  390. this.oldStartDate = this.startDate.clone();
  391. this.oldEndDate = this.endDate.clone();
  392. this.startDate = start;
  393. this.endDate = end;
  394. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  395. this.notify();
  396. this.updateCalendars();
  397. },
  398. notify: function () {
  399. this.updateView();
  400. this.cb(this.startDate, this.endDate, this.chosenLabel);
  401. },
  402. move: function () {
  403. var parentOffset = { top: 0, left: 0 };
  404. var parentRightEdge = $(window).width();
  405. if (!this.parentEl.is('body')) {
  406. parentOffset = {
  407. top: this.parentEl.offset().top - this.parentEl.scrollTop(),
  408. left: this.parentEl.offset().left - this.parentEl.scrollLeft()
  409. };
  410. parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left;
  411. }
  412. if (this.opens == 'left') {
  413. this.container.css({
  414. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  415. right: parentRightEdge - this.element.offset().left - this.element.outerWidth(),
  416. left: 'auto'
  417. });
  418. if (this.container.offset().left < 0) {
  419. this.container.css({
  420. right: 'auto',
  421. left: 9
  422. });
  423. }
  424. } else {
  425. this.container.css({
  426. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  427. left: this.element.offset().left - parentOffset.left,
  428. right: 'auto'
  429. });
  430. if (this.container.offset().left + this.container.outerWidth() > $(window).width()) {
  431. this.container.css({
  432. left: 'auto',
  433. right: 0
  434. });
  435. }
  436. }
  437. },
  438. toggle: function (e) {
  439. if (this.element.hasClass('active')) {
  440. this.hide();
  441. } else {
  442. this.show();
  443. }
  444. },
  445. show: function (e) {
  446. if (this.isShowing) return;
  447. this.element.addClass('active');
  448. this.container.show();
  449. this.move();
  450. // Create a click proxy that is private to this instance of datepicker, for unbinding
  451. this._outsideClickProxy = $.proxy(function (e) { this.outsideClick(e); }, this);
  452. // Bind global datepicker mousedown for hiding and
  453. $(document)
  454. .on('mousedown.daterangepicker', this._outsideClickProxy)
  455. // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
  456. .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
  457. // and also close when focus changes to outside the picker (eg. tabbing between controls)
  458. .on('focusin.daterangepicker', this._outsideClickProxy);
  459. this.isShowing = true;
  460. this.element.trigger('show.daterangepicker', this);
  461. },
  462. outsideClick: function (e) {
  463. var target = $(e.target);
  464. // if the page is clicked anywhere except within the daterangerpicker/button
  465. // itself then call this.hide()
  466. if (
  467. target.closest(this.element).length ||
  468. target.closest(this.container).length ||
  469. target.closest('.calendar-date').length
  470. ) return;
  471. this.hide();
  472. },
  473. hide: function (e) {
  474. if (!this.isShowing) return;
  475. $(document)
  476. .off('mousedown.daterangepicker')
  477. .off('click.daterangepicker', '[data-toggle=dropdown]')
  478. .off('focusin.daterangepicker');
  479. this.element.removeClass('active');
  480. this.container.hide();
  481. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  482. this.notify();
  483. this.oldStartDate = this.startDate.clone();
  484. this.oldEndDate = this.endDate.clone();
  485. this.isShowing = false;
  486. this.element.trigger('hide.daterangepicker', this);
  487. },
  488. enterRange: function (e) {
  489. // mouse pointer has entered a range label
  490. var label = e.target.innerHTML;
  491. if (label == this.locale.customRangeLabel) {
  492. this.updateView();
  493. } else {
  494. var dates = this.ranges[label];
  495. this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.format));
  496. this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.format));
  497. }
  498. },
  499. showCalendars: function() {
  500. this.container.addClass('show-calendar');
  501. this.move();
  502. this.element.trigger('showCalendar.daterangepicker', this);
  503. },
  504. hideCalendars: function() {
  505. this.container.removeClass('show-calendar');
  506. this.element.trigger('hideCalendar.daterangepicker', this);
  507. },
  508. // when a date is typed into the start to end date textboxes
  509. inputsChanged: function (e) {
  510. var el = $(e.target);
  511. var date = moment(el.val(), this.format);
  512. if (!date.isValid()) return;
  513. var startDate, endDate;
  514. if (el.attr('name') === 'daterangepicker_start') {
  515. startDate = date;
  516. endDate = this.endDate;
  517. } else {
  518. startDate = this.startDate;
  519. endDate = date;
  520. }
  521. this.setCustomDates(startDate, endDate);
  522. },
  523. inputsKeydown: function(e) {
  524. if (e.keyCode === 13) {
  525. this.inputsChanged(e);
  526. this.notify();
  527. }
  528. },
  529. updateInputText: function() {
  530. if (this.element.is('input') && !this.singleDatePicker) {
  531. this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
  532. } else if (this.element.is('input')) {
  533. this.element.val(this.endDate.format(this.format));
  534. }
  535. },
  536. clickRange: function (e) {
  537. var label = e.target.innerHTML;
  538. this.chosenLabel = label;
  539. if (label == this.locale.customRangeLabel) {
  540. this.showCalendars();
  541. } else {
  542. var dates = this.ranges[label];
  543. this.startDate = dates[0];
  544. this.endDate = dates[1];
  545. if (!this.timePicker) {
  546. this.startDate.startOf('day');
  547. this.endDate.endOf('day');
  548. }
  549. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
  550. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
  551. this.updateCalendars();
  552. this.updateInputText();
  553. this.hideCalendars();
  554. this.hide();
  555. this.element.trigger('apply.daterangepicker', this);
  556. }
  557. },
  558. clickPrev: function (e) {
  559. var cal = $(e.target).parents('.calendar');
  560. if (cal.hasClass('left')) {
  561. this.leftCalendar.month.subtract(1, 'month');
  562. } else {
  563. this.rightCalendar.month.subtract(1, 'month');
  564. }
  565. this.updateCalendars();
  566. },
  567. clickNext: function (e) {
  568. var cal = $(e.target).parents('.calendar');
  569. if (cal.hasClass('left')) {
  570. this.leftCalendar.month.add(1, 'month');
  571. } else {
  572. this.rightCalendar.month.add(1, 'month');
  573. }
  574. this.updateCalendars();
  575. },
  576. hoverDate: function (e) {
  577. var title = $(e.target).attr('data-title');
  578. var row = title.substr(1, 1);
  579. var col = title.substr(3, 1);
  580. var cal = $(e.target).parents('.calendar');
  581. if (cal.hasClass('left')) {
  582. this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].format(this.format));
  583. } else {
  584. this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].format(this.format));
  585. }
  586. },
  587. setCustomDates: function(startDate, endDate) {
  588. this.chosenLabel = this.locale.customRangeLabel;
  589. if (startDate.isAfter(endDate)) {
  590. var difference = this.endDate.diff(this.startDate);
  591. endDate = moment(startDate).add(difference, 'ms');
  592. }
  593. this.startDate = startDate;
  594. this.endDate = endDate;
  595. this.updateView();
  596. this.updateCalendars();
  597. },
  598. clickDate: function (e) {
  599. var title = $(e.target).attr('data-title');
  600. var row = title.substr(1, 1);
  601. var col = title.substr(3, 1);
  602. var cal = $(e.target).parents('.calendar');
  603. var startDate, endDate;
  604. if (cal.hasClass('left')) {
  605. startDate = this.leftCalendar.calendar[row][col];
  606. endDate = this.endDate;
  607. if (typeof this.dateLimit === 'object') {
  608. var maxDate = moment(startDate).add(this.dateLimit).startOf('day');
  609. if (endDate.isAfter(maxDate)) {
  610. endDate = maxDate;
  611. }
  612. }
  613. } else {
  614. startDate = this.startDate;
  615. endDate = this.rightCalendar.calendar[row][col];
  616. if (typeof this.dateLimit === 'object') {
  617. var minDate = moment(endDate).subtract(this.dateLimit).startOf('day');
  618. if (startDate.isBefore(minDate)) {
  619. startDate = minDate;
  620. }
  621. }
  622. }
  623. if (this.singleDatePicker && cal.hasClass('left')) {
  624. endDate = startDate.clone();
  625. } else if (this.singleDatePicker && cal.hasClass('right')) {
  626. startDate = endDate.clone();
  627. }
  628. cal.find('td').removeClass('active');
  629. $(e.target).addClass('active');
  630. this.setCustomDates(startDate, endDate);
  631. if (!this.timePicker)
  632. endDate.endOf('day');
  633. if (this.singleDatePicker && !this.timePicker)
  634. this.clickApply();
  635. },
  636. clickApply: function (e) {
  637. this.updateInputText();
  638. this.hide();
  639. this.element.trigger('apply.daterangepicker', this);
  640. },
  641. clickCancel: function (e) {
  642. this.startDate = this.oldStartDate;
  643. this.endDate = this.oldEndDate;
  644. this.chosenLabel = this.oldChosenLabel;
  645. this.updateView();
  646. this.updateCalendars();
  647. this.hide();
  648. this.element.trigger('cancel.daterangepicker', this);
  649. },
  650. updateMonthYear: function (e) {
  651. var isLeft = $(e.target).closest('.calendar').hasClass('left'),
  652. leftOrRight = isLeft ? 'left' : 'right',
  653. cal = this.container.find('.calendar.'+leftOrRight);
  654. // Month must be Number for new moment versions
  655. var month = parseInt(cal.find('.monthselect').val(), 10);
  656. var year = cal.find('.yearselect').val();
  657. this[leftOrRight+'Calendar'].month.month(month).year(year);
  658. this.updateCalendars();
  659. },
  660. updateTime: function(e) {
  661. var cal = $(e.target).closest('.calendar'),
  662. isLeft = cal.hasClass('left');
  663. var hour = parseInt(cal.find('.hourselect').val(), 10);
  664. var minute = parseInt(cal.find('.minuteselect').val(), 10);
  665. if (this.timePicker12Hour) {
  666. var ampm = cal.find('.ampmselect').val();
  667. if (ampm === 'PM' && hour < 12)
  668. hour += 12;
  669. if (ampm === 'AM' && hour === 12)
  670. hour = 0;
  671. }
  672. if (isLeft) {
  673. var start = this.startDate.clone();
  674. start.hour(hour);
  675. start.minute(minute);
  676. this.startDate = start;
  677. this.leftCalendar.month.hour(hour).minute(minute);
  678. } else {
  679. var end = this.endDate.clone();
  680. end.hour(hour);
  681. end.minute(minute);
  682. this.endDate = end;
  683. this.rightCalendar.month.hour(hour).minute(minute);
  684. }
  685. this.updateCalendars();
  686. },
  687. updateCalendars: function () {
  688. this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.month(), this.leftCalendar.month.year(), this.leftCalendar.month.hour(), this.leftCalendar.month.minute(), 'left');
  689. this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.month(), this.rightCalendar.month.year(), this.rightCalendar.month.hour(), this.rightCalendar.month.minute(), 'right');
  690. this.container.find('.calendar.left').empty().html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.maxDate));
  691. this.container.find('.calendar.right').empty().html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.singleDatePicker ? this.minDate : this.startDate, this.maxDate));
  692. this.container.find('.ranges li').removeClass('active');
  693. var customRange = true;
  694. var i = 0;
  695. for (var range in this.ranges) {
  696. if (this.timePicker) {
  697. if (this.startDate.isSame(this.ranges[range][0]) && this.endDate.isSame(this.ranges[range][1])) {
  698. customRange = false;
  699. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')')
  700. .addClass('active').html();
  701. }
  702. } else {
  703. //ignore times when comparing dates if time picker is not enabled
  704. 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')) {
  705. customRange = false;
  706. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')')
  707. .addClass('active').html();
  708. }
  709. }
  710. i++;
  711. }
  712. if (customRange) {
  713. this.chosenLabel = this.container.find('.ranges li:last').addClass('active').html();
  714. this.showCalendars();
  715. }
  716. },
  717. buildCalendar: function (month, year, hour, minute, side) {
  718. var daysInMonth = moment([year, month]).daysInMonth();
  719. var firstDay = moment([year, month, 1]);
  720. var lastDay = moment([year, month, daysInMonth]);
  721. var lastMonth = moment(firstDay).subtract(1, 'month').month();
  722. var lastYear = moment(firstDay).subtract(1, 'month').year();
  723. var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
  724. var dayOfWeek = firstDay.day();
  725. var i;
  726. //initialize a 6 rows x 7 columns array for the calendar
  727. var calendar = [];
  728. calendar.firstDay = firstDay;
  729. calendar.lastDay = lastDay;
  730. for (i = 0; i < 6; i++) {
  731. calendar[i] = [];
  732. }
  733. //populate the calendar with date objects
  734. var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
  735. if (startDay > daysInLastMonth)
  736. startDay -= 7;
  737. if (dayOfWeek == this.locale.firstDay)
  738. startDay = daysInLastMonth - 6;
  739. var curDate = moment([lastYear, lastMonth, startDay, 12, minute]);
  740. var col, row;
  741. for (i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) {
  742. if (i > 0 && col % 7 === 0) {
  743. col = 0;
  744. row++;
  745. }
  746. calendar[row][col] = curDate.clone().hour(hour);
  747. curDate.hour(12);
  748. }
  749. return calendar;
  750. },
  751. renderDropdowns: function (selected, minDate, maxDate) {
  752. var currentMonth = selected.month();
  753. var monthHtml = '<select class="monthselect">';
  754. var inMinYear = false;
  755. var inMaxYear = false;
  756. for (var m = 0; m < 12; m++) {
  757. if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) {
  758. monthHtml += "<option value='" + m + "'" +
  759. (m === currentMonth ? " selected='selected'" : "") +
  760. ">" + this.locale.monthNames[m] + "</option>";
  761. }
  762. }
  763. monthHtml += "</select>";
  764. var currentYear = selected.year();
  765. var maxYear = (maxDate && maxDate.year()) || (currentYear + 5);
  766. var minYear = (minDate && minDate.year()) || (currentYear - 50);
  767. var yearHtml = '<select class="yearselect">';
  768. for (var y = minYear; y <= maxYear; y++) {
  769. yearHtml += '<option value="' + y + '"' +
  770. (y === currentYear ? ' selected="selected"' : '') +
  771. '>' + y + '</option>';
  772. }
  773. yearHtml += '</select>';
  774. return monthHtml + yearHtml;
  775. },
  776. renderCalendar: function (calendar, selected, minDate, maxDate) {
  777. var html = '<div class="calendar-date">';
  778. html += '<table class="table-condensed">';
  779. html += '<thead>';
  780. html += '<tr>';
  781. // add empty cell for week number
  782. if (this.showWeekNumbers)
  783. html += '<th></th>';
  784. if (!minDate || minDate.isBefore(calendar.firstDay)) {
  785. html += '<th class="prev available"><i class="fa fa-angle-left"></i></th>';
  786. } else {
  787. html += '<th></th>';
  788. }
  789. var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
  790. if (this.showDropdowns) {
  791. dateHtml = this.renderDropdowns(calendar[1][1], minDate, maxDate);
  792. }
  793. html += '<th colspan="5" class="month">' + dateHtml + '</th>';
  794. if (!maxDate || maxDate.isAfter(calendar.lastDay)) {
  795. html += '<th class="next available"><i class="fa fa-angle-right"></i></th>';
  796. } else {
  797. html += '<th></th>';
  798. }
  799. html += '</tr>';
  800. html += '<tr>';
  801. // add week number label
  802. if (this.showWeekNumbers)
  803. html += '<th class="week">' + this.locale.weekLabel + '</th>';
  804. $.each(this.locale.daysOfWeek, function (index, dayOfWeek) {
  805. html += '<th>' + dayOfWeek + '</th>';
  806. });
  807. html += '</tr>';
  808. html += '</thead>';
  809. html += '<tbody>';
  810. for (var row = 0; row < 6; row++) {
  811. html += '<tr>';
  812. // add week number
  813. if (this.showWeekNumbers)
  814. html += '<td class="week">' + calendar[row][0].week() + '</td>';
  815. for (var col = 0; col < 7; col++) {
  816. var cname = 'available ';
  817. cname += (calendar[row][col].month() == calendar[1][1].month()) ? '' : 'off';
  818. if ((minDate && calendar[row][col].isBefore(minDate, 'day')) || (maxDate && calendar[row][col].isAfter(maxDate, 'day'))) {
  819. cname = ' off disabled ';
  820. } else if (calendar[row][col].format('YYYY-MM-DD') == selected.format('YYYY-MM-DD')) {
  821. cname += ' active ';
  822. if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD')) {
  823. cname += ' start-date ';
  824. }
  825. if (calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD')) {
  826. cname += ' end-date ';
  827. }
  828. } else if (calendar[row][col] >= this.startDate && calendar[row][col] <= this.endDate) {
  829. cname += ' in-range ';
  830. if (calendar[row][col].isSame(this.startDate)) { cname += ' start-date '; }
  831. if (calendar[row][col].isSame(this.endDate)) { cname += ' end-date '; }
  832. }
  833. var title = 'r' + row + 'c' + col;
  834. html += '<td class="' + cname.replace(/\s+/g, ' ').replace(/^\s?(.*?)\s?$/, '$1') + '" data-title="' + title + '">' + calendar[row][col].date() + '</td>';
  835. }
  836. html += '</tr>';
  837. }
  838. html += '</tbody>';
  839. html += '</table>';
  840. html += '</div>';
  841. var i;
  842. if (this.timePicker) {
  843. html += '<div class="calendar-time">';
  844. html += '<select class="hourselect">';
  845. var start = 0;
  846. var end = 23;
  847. var selected_hour = selected.hour();
  848. if (this.timePicker12Hour) {
  849. start = 1;
  850. end = 12;
  851. if (selected_hour >= 12)
  852. selected_hour -= 12;
  853. if (selected_hour === 0)
  854. selected_hour = 12;
  855. }
  856. for (i = start; i <= end; i++) {
  857. if (i == selected_hour) {
  858. html += '<option value="' + i + '" selected="selected">' + i + '</option>';
  859. } else {
  860. html += '<option value="' + i + '">' + i + '</option>';
  861. }
  862. }
  863. html += '</select> : ';
  864. html += '<select class="minuteselect">';
  865. for (i = 0; i < 60; i += this.timePickerIncrement) {
  866. var num = i;
  867. if (num < 10)
  868. num = '0' + num;
  869. if (i == selected.minute()) {
  870. html += '<option value="' + i + '" selected="selected">' + num + '</option>';
  871. } else {
  872. html += '<option value="' + i + '">' + num + '</option>';
  873. }
  874. }
  875. html += '</select> ';
  876. if (this.timePicker12Hour) {
  877. html += '<select class="ampmselect">';
  878. if (selected.hour() >= 12) {
  879. html += '<option value="AM">AM</option><option value="PM" selected="selected">PM</option>';
  880. } else {
  881. html += '<option value="AM" selected="selected">AM</option><option value="PM">PM</option>';
  882. }
  883. html += '</select>';
  884. }
  885. html += '</div>';
  886. }
  887. return html;
  888. },
  889. remove: function() {
  890. this.container.remove();
  891. this.element.off('.daterangepicker');
  892. this.element.removeData('daterangepicker');
  893. }
  894. };
  895. $.fn.daterangepicker = function (options, cb) {
  896. this.each(function () {
  897. var el = $(this);
  898. if (el.data('daterangepicker'))
  899. el.data('daterangepicker').remove();
  900. el.data('daterangepicker', new DateRangePicker(el, options, cb));
  901. });
  902. return this;
  903. };
  904. }));