daterangepicker.js 68 KB

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