daterangepicker.js 63 KB

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