daterangepicker.js 33 KB

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