daterangepicker.js 69 KB

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