How to disable the previous dates in the java script calender..? - javascript

I am using a javascript calender in my project. It is working perfectly. But i want to disable the previous dates in the calender. Code used for that calender is as below..
/* Code starts here*/
var datepickr = (function() {
var datepickrs = [],
currentDate = new Date(),
date = {
current: {
year: function() {
return currentDate.getFullYear();
},
month: {
integer: function() {
return currentDate.getMonth();
},
string: function(full) {
var date = currentDate.getMonth();
return monthToStr(date, full);
}
},
day: function() {
return currentDate.getDate();
}
},
month: {
string: function(full, currentMonthView) {
var date = currentMonthView;
return monthToStr(date, full);
},
numDays: function(currentMonthView, currentYearView) {
// checks to see if february is a leap year otherwise return the respective # of days
return (currentMonthView == 1 && !(currentYearView & 3) && (currentYearView % 1e2 || !(currentYearView % 4e2))) ? 29 : daysInMonth[currentMonthView];
}
}
},
weekdays = ['Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur'],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
suffix = { 1: 'st', 2: 'nd', 3: 'rd', 21: 'st', 22: 'nd', 23: 'rd', 31: 'st' },
buildCache = [],
handlers = {
calendarClick: function(e) {
if(e.target.className) {
switch(e.target.className) {
case 'prev-month':
case 'prevMonth':
this.currentMonthView--;
if(this.currentMonthView < 0) {
this.currentYearView--;
this.currentMonthView = 11;
}
rebuildCalendar.call(this);
break;
case 'next-month':
case 'nextMonth':
this.currentMonthView++;
if(this.currentMonthView > 11) {
this.currentYearView++;
this.currentMonthView = 0;
}
rebuildCalendar.call(this);
break;
case 'day':
this.element.value = formatDate(new Date(this.currentYearView, this.currentMonthView, e.target.innerHTML).getTime(), this.config.dateFormat);
this.close();
break;
}
}
},
documentClick: function(e) {
if(e.target != this.element && e.target != this.calendar) {
var parentNode = e.target.parentNode;
if(parentNode != this.calender) {
while(parentNode != this.calendar) {
parentNode = parentNode.parentNode;
if(parentNode == null) {
this.close();
break;
}
}
}
}
}
};
function formatDate(milliseconds, dateFormat) {
var formattedDate = '',
dateObj = new Date(milliseconds),
format = {
d: function() {
var day = format.j();
return (day < 10) ? '0' + day : day;
},
D: function() {
return weekdays[format.w()].substring(0, 3);
},
j: function() {
return dateObj.getDate();
},
l: function() {
return weekdays[format.w()] + 'day';
},
S: function() {
return suffix[format.j()] || 'th';
},
w: function() {
return dateObj.getDay();
},
F: function() {
return monthToStr(format.n(), true);
},
m: function() {
var month = format.n() + 1;
return (month < 10) ? '0' + month : month;
},
M: function() {
return monthToStr(format.n(), false);
},
n: function() {
return dateObj.getMonth();
},
Y: function() {
return dateObj.getFullYear();
},
y: function() {
return format.Y().toString().substring(2, 4);
}
},
formatPieces = dateFormat.split('');
foreach(formatPieces, function(formatPiece) {
formattedDate += format[formatPiece] ? format[formatPiece]() : formatPiece;
});
return formattedDate;
}
function foreach(items, callback) {
var i = 0, x = items.length;
for(i; i < x; i++) {
if(callback(items[i], i) === false) {
break;
}
}
}
function addEvent(element, eventType, callback) {
if(element.addEventListener) {
element.addEventListener(eventType, callback, false);
} else if(element.attachEvent) {
var fixedCallback = function(e) {
e = e || window.event;
e.preventDefault = (function(e) {
return function() { e.returnValue = false; }
})(e);
e.stopPropagation = (function(e) {
return function() { e.cancelBubble = true; }
})(e);
e.target = e.srcElement;
callback.call(element, e);
};
element.attachEvent('on' + eventType, fixedCallback);
}
}
function removeEvent(element, eventType, callback) {
if(element.removeEventListener) {
element.removeEventListener(eventType, callback, false);
} else if(element.detachEvent) {
element.detachEvent('on' + eventType, callback);
}
}
function buildNode(nodeName, attributes, content) {
var element;
if(!(nodeName in buildCache)) {
buildCache[nodeName] = document.createElement(nodeName);
}
element = buildCache[nodeName].cloneNode(false);
if(attributes != null) {
for(var attribute in attributes) {
element[attribute] = attributes[attribute];
}
}
if(content != null) {
if(typeof(content) == 'object') {
element.appendChild(content);
} else {
element.innerHTML = content;
}
}
return element;
}
function monthToStr(date, full) {
return ((full == true) ? months[date] : ((months[date].length > 3) ? months[date].substring(0, 3) : months[date]));
}
function isToday(day, currentMonthView, currentYearView) {
return day == date.current.day() && currentMonthView == date.current.month.integer() && currentYearView == date.current.year();
}
function buildWeekdays() {
var weekdayHtml = document.createDocumentFragment();
foreach(weekdays, function(weekday) {
weekdayHtml.appendChild(buildNode('th', {}, weekday.substring(0, 2)));
});
return weekdayHtml;
}
function rebuildCalendar() {
while(this.calendarBody.hasChildNodes()){
this.calendarBody.removeChild(this.calendarBody.lastChild);
}
var firstOfMonth = new Date(this.currentYearView, this.currentMonthView, 1).getDay(),
numDays = date.month.numDays(this.currentMonthView, this.currentYearView);
this.currentMonth.innerHTML = date.month.string(this.config.fullCurrentMonth, this.currentMonthView) + ' ' + this.currentYearView;
this.calendarBody.appendChild(buildDays(firstOfMonth, numDays, this.currentMonthView, this.currentYearView));
}
function buildCurrentMonth(config, currentMonthView, currentYearView) {
return buildNode('span', { className: 'current-month' }, date.month.string(config.fullCurrentMonth, currentMonthView) + ' ' + currentYearView);
}
function buildMonths(config, currentMonthView, currentYearView) {
var months = buildNode('div', { className: 'months' }),
prevMonth = buildNode('span', { className: 'prev-month' }, buildNode('span', { className: 'prevMonth' }, '<')),
nextMonth = buildNode('span', { className: 'next-month' }, buildNode('span', { className: 'nextMonth' }, '>'));
months.appendChild(prevMonth);
months.appendChild(nextMonth);
return months;
}
function buildDays(firstOfMonth, numDays, currentMonthView, currentYearView) {
var calendarBody = document.createDocumentFragment(),
row = buildNode('tr'),
dayCount = 0, i;
// print out previous month's "days"
for(i = 1; i <= firstOfMonth; i++) {
row.appendChild(buildNode('td', null, ' '));
dayCount++;
}
for(i = 1; i <= numDays; i++) {
// if we have reached the end of a week, wrap to the next line
if(dayCount == 7) {
calendarBody.appendChild(row);
row = buildNode('tr');
dayCount = 0;
}
var todayClassName = isToday(i, currentMonthView, currentYearView) ? { className: 'today' } : null;
row.appendChild(buildNode('td', todayClassName, buildNode('span', { className: 'day' }, i)));
dayCount++;
}
// if we haven't finished at the end of the week, start writing out the "days" for the next month
for(i = 1; i <= (7 - dayCount); i++) {
row.appendChild(buildNode('td', null, ' '));
}
calendarBody.appendChild(row);
return calendarBody;
}
function buildCalendar() {
var firstOfMonth = new Date(this.currentYearView, this.currentMonthView, 1).getDay(),
numDays = date.month.numDays(this.currentMonthView, this.currentYearView),
self = this;
var inputLeft = inputTop = 0,
obj = this.element;
if(obj.offsetParent) {
do {
inputLeft += obj.offsetLeft;
inputTop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
var calendarContainer = buildNode('div', { className: 'calendar' });
calendarContainer.style.cssText = 'display: none; position: absolute; top: ' + (inputTop + this.element.offsetHeight) + 'px; left: ' + inputLeft + 'px; z-index: 100;';
this.currentMonth = buildCurrentMonth(this.config, this.currentMonthView, this.currentYearView)
var months = buildMonths(this.config, this.currentMonthView, this.currentYearView);
months.appendChild(this.currentMonth);
var calendar = buildNode('table', null, buildNode('thead', null, buildNode('tr', { className: 'weekdays' }, buildWeekdays())));
this.calendarBody = buildNode('tbody');
this.calendarBody.appendChild(buildDays(firstOfMonth, numDays, this.currentMonthView, this.currentYearView));
calendar.appendChild(this.calendarBody);
calendarContainer.appendChild(months);
calendarContainer.appendChild(calendar);
document.body.appendChild(calendarContainer);
addEvent(calendarContainer, 'click', function(e) { handlers.calendarClick.call(self, e); });
return calendarContainer;
}
return function(elementId, userConfig) {
var self = this;
this.element = document.getElementById(elementId);
this.config = {
fullCurrentMonth: true,
dateFormat: 'F jS, Y'
};
this.currentYearView = date.current.year();
this.currentMonthView = date.current.month.integer();
if(userConfig) {
for(var key in userConfig) {
if(this.config.hasOwnProperty(key)) {
this.config[key] = userConfig[key];
}
}
}
this.documentClick = function(e) { handlers.documentClick.call(self, e); }
this.open = function(e) {
addEvent(document, 'click', self.documentClick);
foreach(datepickrs, function(datepickr) {
if(datepickr != self) {
datepickr.close();
}
});
self.calendar.style.display = 'block';
}
this.close = function() {
removeEvent(document, 'click', self.documentClick);
self.calendar.style.display = 'none';
}
this.calendar = buildCalendar.call(this);
datepickrs.push(this);
if(this.element.nodeName == 'INPUT') {
addEvent(this.element, 'focus', this.open);
} else {
addEvent(this.element, 'click', this.open);
}
}
})();
/* Code Ends here*/
In the above code do i want to add something more or want to change something..?
Please let me know..
Thanks in advance,
Sree ram.

The following code should prevent any dates prior to the current date from being selectable.
$('#element').datepicker({
minDate: new Date()
});
Hopefully this answers your question.

Related

Disabled past months in monthpicker

I have a monthpicker something like datepicker and I want to disable past days or I have reserved day and and I want to give them to class.
My codes are below but I guess related code is this
$('#monthpicker').monthpicker().on('monthpicker-change-year', function(e, year) {
$('#monthpicker').monthpicker('disableMonths', [1, 2, 3, 4]); // (re)enables all
if (year === '2017') {
$('#monthpicker').monthpicker('disableMonths', [1, 2, 3, 4]);
}
if (year === '2019') {
$('#monthpicker').monthpicker('disableMonths', [9, 10, 11, 12]);
}
});
and this is the all code
(function($) {
var methods = {
init: function(options) {
return this.each(function() {
var
$this = $(this),
data = $this.data('monthpicker'),
year = (options && options.year) ? options.year : (new Date()).getFullYear(),
settings = $.extend({
pattern: 'mm/yyyy',
selectedMonth: null,
selectedMonthName: '',
selectedYear: year,
startYear: year - 10,
finalYear: year + 10,
monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
id: "monthpicker_" + (Math.random() * Math.random()).toString().replace('.', ''),
openOnFocus: true,
disabledMonths: []
}, options);
settings.dateSeparator = settings.pattern.replace(/(mmm|mm|m|yyyy|yy|y)/ig, '');
// If the plugin hasn't been initialized yet for this element
if (!data) {
$(this).data('monthpicker', {
'target': $this,
'settings': settings
});
if (settings.openOnFocus === true) {
$this.on('focus', function() {
$this.monthpicker('show');
});
}
$this.monthpicker('parseInputValue', settings);
$this.monthpicker('mountWidget', settings);
$this.on('monthpicker-click-month', function(e, month, year) {
$this.monthpicker('setValue', settings);
$this.monthpicker('hide');
});
// hide widget when user clicks elsewhere on page
$this.addClass("mtz-monthpicker-widgetcontainer");
$(document).unbind("mousedown.mtzmonthpicker").on("mousedown.mtzmonthpicker", function(e) {
if (!e.target.className || e.target.className.toString().indexOf('mtz-monthpicker') < 0) {
$(this).monthpicker('hideAll');
}
});
}
});
},
show: function() {
$(this).monthpicker('hideAll');
var widget = $('#' + this.data('monthpicker').settings.id);
widget.css("top", this.offset().top + this.outerHeight());
if ($(window).width() > (widget.width() + this.offset().left)) {
widget.css("left", this.offset().left);
} else {
widget.css("left", this.offset().left - widget.width());
}
widget.show();
widget.find('select').focus();
this.trigger('monthpicker-show');
},
hide: function() {
var widget = $('#' + this.data('monthpicker').settings.id);
if (widget.is(':visible')) {
widget.hide();
this.trigger('monthpicker-hide');
}
},
hideAll: function() {
$(".mtz-monthpicker-widgetcontainer").each(function() {
if (typeof($(this).data("monthpicker")) != "undefined") {
$(this).monthpicker('hide');
}
});
},
setValue: function(settings) {
var
month = settings.selectedMonth,
year = settings.selectedYear;
if (settings.pattern.indexOf('mmm') >= 0) {
month = settings.selectedMonthName;
} else if (settings.pattern.indexOf('mm') >= 0 && settings.selectedMonth < 10) {
month = '0' + settings.selectedMonth;
}
if (settings.pattern.indexOf('yyyy') < 0) {
year = year.toString().substr(2, 2);
}
if (settings.pattern.indexOf('y') > settings.pattern.indexOf(settings.dateSeparator)) {
this.val(month + settings.dateSeparator + year);
} else {
this.val(year + settings.dateSeparator + month);
}
this.change();
},
disableMonths: function(months) {
var
settings = this.data('monthpicker').settings,
container = $('#' + settings.id);
settings.disabledMonths = months;
container.find('.mtz-monthpicker-month').each(function() {
var m = parseInt($(this).data('month'));
if ($.inArray(m, months) >= 0) {
$(this).addClass('ui-state-disabled');
} else {
$(this).removeClass('ui-state-disabled');
}
});
},
mountWidget: function(settings) {
var
monthpicker = this,
container = $('<div id="' + settings.id + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" />'),
header = $('<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-all mtz-monthpicker" />'),
combo = $('<select class="mtz-monthpicker mtz-monthpicker-year" />'),
table = $('<table class="mtz-monthpicker" />'),
tbody = $('<tbody class="mtz-monthpicker" />'),
tr = $('<tr class="mtz-monthpicker" />'),
td = '',
selectedYear = settings.selectedYear,
option = null,
attrSelectedYear = $(this).data('selected-year'),
attrStartYear = $(this).data('start-year'),
attrFinalYear = $(this).data('final-year');
if (attrSelectedYear) {
settings.selectedYear = attrSelectedYear;
}
if (attrStartYear) {
settings.startYear = attrStartYear;
}
if (attrFinalYear) {
settings.finalYear = attrFinalYear;
}
container.css({
position: 'absolute',
zIndex: 999999,
whiteSpace: 'nowrap',
width: '250px',
overflow: 'hidden',
textAlign: 'center',
display: 'none',
top: monthpicker.offset().top + monthpicker.outerHeight(),
left: monthpicker.offset().left
});
combo.on('change', function() {
var months = $(this).parent().parent().find('td[data-month]');
months.removeClass('ui-state-active');
if ($(this).val() == settings.selectedYear) {
months.filter('td[data-month=' + settings.selectedMonth + ']').addClass('ui-state-active');
}
monthpicker.trigger('monthpicker-change-year', $(this).val());
});
// mount years combo
for (var i = settings.startYear; i <= settings.finalYear; i++) {
var option = $('<option class="mtz-monthpicker" />').attr('value', i).append(i);
if (settings.selectedYear == i) {
option.attr('selected', 'selected');
}
combo.append(option);
}
header.append(combo).appendTo(container);
// mount months table
for (var i = 1; i <= 12; i++) {
td = $('<td class="ui-state-default mtz-monthpicker mtz-monthpicker-month" style="padding:5px;cursor:default;" />').attr('data-month', i);
if (settings.selectedMonth == i) {
td.addClass('ui-state-active');
}
td.append(settings.monthNames[i - 1]);
tr.append(td).appendTo(tbody);
if (i % 3 === 0) {
tr = $('<tr class="mtz-monthpicker" />');
}
}
tbody.find('.mtz-monthpicker-month').on('click', function() {
var m = parseInt($(this).data('month'));
if ($.inArray(m, settings.disabledMonths) < 0) {
settings.selectedYear = $(this).closest('.ui-datepicker').find('.mtz-monthpicker-year').first().val();
settings.selectedMonth = $(this).data('month');
settings.selectedMonthName = $(this).text();
monthpicker.trigger('monthpicker-click-month', $(this).data('month'));
$(this).closest('table').find('.ui-state-active').removeClass('ui-state-active');
$(this).addClass('ui-state-active');
}
});
table.append(tbody).appendTo(container);
container.appendTo('body');
},
destroy: function() {
return this.each(function() {
$(this).removeClass('mtz-monthpicker-widgetcontainer').unbind('focus').removeData('monthpicker');
});
},
getDate: function() {
var settings = this.data('monthpicker').settings;
if (settings.selectedMonth && settings.selectedYear) {
return new Date(settings.selectedYear, settings.selectedMonth - 1);
} else {
return null;
}
},
parseInputValue: function(settings) {
if (this.val()) {
if (settings.dateSeparator) {
var val = this.val().toString().split(settings.dateSeparator);
if (settings.pattern.indexOf('m') === 0) {
settings.selectedMonth = val[0];
settings.selectedYear = val[1];
} else {
settings.selectedMonth = val[1];
settings.selectedYear = val[0];
}
}
}
}
};
$.fn.monthpicker = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.mtz.monthpicker');
}
};
})(jQuery);
$('#monthpicker').monthpicker().on('monthpicker-change-year', function(e, year) {
$('#monthpicker').monthpicker('disableMonths', [1, 2, 3, 4]); // (re)enables all
if (year === '2017') {
$('#monthpicker').monthpicker('disableMonths', [1, 2, 3, 4]);
}
if (year === '2019') {
$('#monthpicker').monthpicker('disableMonths', [9, 10, 11, 12]);
}
});
<input type="text" id="monthpicker" placeholder=" When? ">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript Datepicker - Selecting date then time

Please be aware that I am a total noob at JS, sorry if I don't understand basic coding language. Solutions are very welcome. Thanks!
I have created my own form and have two input fields which consist of 'date of incident' and 'time of incident'. The user will need to select a date either the current date or previous dates only. Then the user will select a time and if the user selected the current date it can only be before the current time. Otherwise anytime is ok.
I have already developed the datepicker for 'date of incident' but I need all the dates after the current date to be grayed out, im not sure if I will need to use 'minDate' or 'maxDate' for this and if I will need to implement it to a existing function or create a new one.
For the 'time of incident' I am using 'type="time".
I have got a little bit of an idea for the date of incident:
currentDate = today
futureDates = greyed out
but I am starting out with JavaScript and don't really know how to implement it properly into the code.
HTML:
<input id="datepick" placeholder="Enter the date of incident" type="text"/>
<input id="timepick" placeholder="Enter the time of incident" type="time"/>
Javascript for Datepicker:
var datepickr = (function() {
var datepickrs = [],
currentDate = new Date(),
date = {
current: {
year: function() {
return currentDate.getFullYear();
},
month: {
integer: function() {
return currentDate.getMonth();
},
string: function(full, months) {
var date = currentDate.getMonth();
return monthToStr(date, full, months);
minDate: currentDate;
}
},
day: function() {
return currentDate.getDate();
}
},
month: {
string: function(full, currentMonthView, months) {
var date = currentMonthView;
return monthToStr(date, full, months);
},
numDays: function(currentMonthView, currentYearView) {
/* checks to see if february is a leap year otherwise return the respective # of days */
return (currentMonthView == 1 && !(currentYearView & 3) && (currentYearView % 1e2 || !(currentYearView % 4e2))) ? 29 : daysInMonth[currentMonthView];
}
}
},
daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
buildCache = [],
handlers = {
calendarClick: function(e) {
if(e.target.className) {
switch(e.target.className) {
case 'prev-month':
case 'prevMonth':
this.currentMonthView--;
if(this.currentMonthView < 0) {
this.currentYearView--;
this.currentMonthView = 11;
}
rebuildCalendar.call(this);
break;
case 'next-month':
case 'nextMonth':
this.currentMonthView++;
if(this.currentMonthView > 11) {
this.currentYearView++;
this.currentMonthView = 0;
}
rebuildCalendar.call(this);
break;
case 'day':
this.element.value = formatDate(new Date(this.currentYearView, this.currentMonthView, e.target.innerHTML).getTime(), this.config);
this.close();
break;
}
}
},
documentClick: function(e) {
if(e.target != this.element && e.target != this.calendar) {
var parentNode = e.target.parentNode;
if(parentNode != this.calender) {
while(parentNode != this.calendar) {
parentNode = parentNode.parentNode;
if(parentNode == null) {
this.close();
break;
}
}
}
}
}
};
function formatDate(milliseconds, config) {
var formattedDate = '',
dateObj = new Date(milliseconds),
format = {
d: function() {
var day = format.j();
return (day < 10) ? '0' + day : day;
},
D: function() {
return config.weekdays[format.w()].substring(0, 3);
},
j: function() {
return dateObj.getDate();
},
l: function() {
return config.weekdays[format.w()];
},
S: function() {
return config.suffix[format.j()] || config.defaultSuffix;
},
w: function() {
return dateObj.getDay();
},
F: function() {
return monthToStr(format.n(), true, config.months);
},
m: function() {
var month = format.n() + 1;
return (month < 10) ? '0' + month : month;
},
M: function() {
return monthToStr(format.n(), false, config.months);
},
n: function() {
return dateObj.getMonth();
},
Y: function() {
return dateObj.getFullYear();
},
y: function() {
return format.Y().toString().substring(2, 4);
}
},
formatPieces = config.dateFormat.split('');
foreach(formatPieces, function(formatPiece, index) {
if(format[formatPiece] && formatPieces[index - 1] != '\\') {
formattedDate += format[formatPiece]();
} else {
if(formatPiece != '\\') {
formattedDate += formatPiece;
}
}
});
return formattedDate;
}
function foreach(items, callback) {
var i = 0, x = items.length;
for(i; i < x; i++) {
if(callback(items[i], i) === false) {
break;
}
}
}
function addEvent(element, eventType, callback) {
if(element.addEventListener) {
element.addEventListener(eventType, callback, false);
} else if(element.attachEvent) {
var fixedCallback = function(e) {
e = e || window.event;
e.preventDefault = (function(e) {
return function() { e.returnValue = false; }
})(e);
e.stopPropagation = (function(e) {
return function() { e.cancelBubble = true; }
})(e);
e.target = e.srcElement;
callback.call(element, e);
};
element.attachEvent('on' + eventType, fixedCallback);
}
}
function removeEvent(element, eventType, callback) {
if(element.removeEventListener) {
element.removeEventListener(eventType, callback, false);
} else if(element.detachEvent) {
element.detachEvent('on' + eventType, callback);
}
}
function buildNode(nodeName, attributes, content) {
var element;
if(!(nodeName in buildCache)) {
buildCache[nodeName] = document.createElement(nodeName);
}
element = buildCache[nodeName].cloneNode(false);
if(attributes != null) {
for(var attribute in attributes) {
element[attribute] = attributes[attribute];
}
}
if(content != null) {
if(typeof(content) == 'object') {
element.appendChild(content);
} else {
element.innerHTML = content;
}
}
return element;
}
function monthToStr(date, full, months) {
return ((full == true) ? months[date] : ((months[date].length > 3) ? months[date].substring(0, 3) : months[date]));
}
function isToday(day, currentMonthView, currentYearView) {
return day == date.current.day() && currentMonthView == date.current.month.integer() && currentYearView == date.current.year();
}
function buildWeekdays(weekdays) {
var weekdayHtml = document.createDocumentFragment();
foreach(weekdays, function(weekday) {
weekdayHtml.appendChild(buildNode('th', {}, weekday.substring(0, 2)));
});
return weekdayHtml;
}
function rebuildCalendar() {
while(this.calendarBody.hasChildNodes()){
this.calendarBody.removeChild(this.calendarBody.lastChild);
}
var firstOfMonth = new Date(this.currentYearView, this.currentMonthView, 1).getDay(),
numDays = date.month.numDays(this.currentMonthView, this.currentYearView);
this.currentMonth.innerHTML = date.month.string(this.config.fullCurrentMonth, this.currentMonthView, this.config.months) + ' ' + this.currentYearView;
this.calendarBody.appendChild(buildDays(firstOfMonth, numDays, this.currentMonthView, this.currentYearView));
}
function buildCurrentMonth(config, currentMonthView, currentYearView, months) {
return buildNode('span', { className: 'current-month' }, date.month.string(config.fullCurrentMonth, currentMonthView, months) + ' ' + currentYearView);
}
function buildMonths(config, currentMonthView, currentYearView) {
var months = buildNode('div', { className: 'months' }),
prevMonth = buildNode('span', { className: 'prev-month' }, buildNode('span', { className: 'prevMonth' }, '<')),
nextMonth = buildNode('span', { className: 'next-month' }, buildNode('span', { className: 'nextMonth' }, '>'));
months.appendChild(prevMonth);
months.appendChild(nextMonth);
return months;
}
function buildDays(firstOfMonth, numDays, currentMonthView, currentYearView) {
var calendarBody = document.createDocumentFragment(),
row = buildNode('tr'),
dayCount = 0, i;
/* print out previous month's "days" */
for(i = 1; i <= firstOfMonth; i++) {
row.appendChild(buildNode('td', null, ' '));
dayCount++;
}
for(i = 1; i <= numDays; i++) {
/* if we have reached the end of a week, wrap to the next line */
if(dayCount == 7) {
calendarBody.appendChild(row);
row = buildNode('tr');
dayCount = 0;
}
var todayClassName = isToday(i, currentMonthView, currentYearView) ? { className: 'today' } : null;
row.appendChild(buildNode('td', todayClassName, buildNode('span', { className: 'day' }, i)));
dayCount++;
}
/* if we haven't finished at the end of the week, start writing out the "days" for the next month */
for(i = 1; i <= (7 - dayCount); i++) {
row.appendChild(buildNode('td', null, ' '));
}
calendarBody.appendChild(row);
return calendarBody;
}
function buildCalendar() {
var firstOfMonth = new Date(this.currentYearView, this.currentMonthView, 1).getDay(),
numDays = date.month.numDays(this.currentMonthView, this.currentYearView),
self = this;
var inputLeft = inputTop = 0,
obj = this.element;
if(obj.offsetParent) {
do {
inputLeft += obj.offsetLeft;
inputTop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
var calendarContainer = buildNode('div', { className: 'calendar' });
calendarContainer.style.cssText = 'display: none; position: absolute; top: ' + (inputTop + this.element.offsetHeight) + 'px; left: ' + inputLeft + 'px; z-index: 100;';
this.currentMonth = buildCurrentMonth(this.config, this.currentMonthView, this.currentYearView, this.config.months)
var months = buildMonths(this.config, this.currentMonthView, this.currentYearView);
months.appendChild(this.currentMonth);
var calendar = buildNode('table', null, buildNode('thead', null, buildNode('tr', { className: 'weekdays' }, buildWeekdays(this.config.weekdays))));
this.calendarBody = buildNode('tbody');
this.calendarBody.appendChild(buildDays(firstOfMonth, numDays, this.currentMonthView, this.currentYearView));
calendar.appendChild(this.calendarBody);
calendarContainer.appendChild(months);
calendarContainer.appendChild(calendar);
document.body.appendChild(calendarContainer);
addEvent(calendarContainer, 'click', function(e) { handlers.calendarClick.call(self, e); });
return calendarContainer;
}
return function(elementId, userConfig) {
var self = this;
this.element = document.getElementById(elementId);
this.config = {
fullCurrentMonth: true,
dateFormat: 'F jS, Y',
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
suffix: { 1: 'st', 2: 'nd', 3: 'rd', 21: 'st', 22: 'nd', 23: 'rd', 31: 'st' },
defaultSuffix: 'th'
};
this.currentYearView = date.current.year();
this.currentMonthView = date.current.month.integer();
if(userConfig) {
for(var key in userConfig) {
if(this.config.hasOwnProperty(key)) {
this.config[key] = userConfig[key];
}
}
}
this.documentClick = function(e) { handlers.documentClick.call(self, e); }
this.open = function(e) {
addEvent(document, 'click', self.documentClick);
foreach(datepickrs, function(datepickr) {
if(datepickr != self) {
datepickr.close();
}
});
self.calendar.style.display = 'block';
}
this.close = function() {
removeEvent(document, 'click', self.documentClick);
self.calendar.style.display = 'none';
}
this.calendar = buildCalendar.call(this);
datepickrs.push(this);
if(this.element.nodeName == 'INPUT') {
addEvent(this.element, 'focus', this.open);
} else {
addEvent(this.element, 'click', this.open);
}
}
})();
Sorry I don't have any code for my 'Time of Incident' field but I have a small psuedocode that I would like to turn into JavaScript and implement it into my code:
currentDate = new Date()
currentTime = new Date(time)
function timeSelect{
if{
datepicker = currentDate
{
time = currentTime (Can't select time past now, greyed out)
else
{
any time can be selected
}
Thank you for your time, it really helps me out.
-MrMaestro

Javascript Datepicker - disabling future dates

Just a little bit of a disclaimer: I'm pretty much a noob at JavaScript and followed a bit of a guide for my datepicker. Please go easy on me.
I have developed a form (with my knowledge) and I have implemented a custom developed JavaScript datepicker for my 'date of incident' field.
For this field I have gotten the date to work but I need to code the datepicker so that the user cannot select any date after the currant date, only previous dates before the currant date and should also accept the currant date.
I am thinking if I could use 'minDate' or 'maxDate'? (If that's possible without jQuery)
Please note I am only using JavaScript and not jQuery or Bootstrap.
Here is the HTML and JavaScript for my datepicker code, I am not sure whether to create a new function or implement it in my currant one (It's a lot of code)
HTML:
<label>Date of Incident:</label><input id="datepick" placeholder="Enter the date of incident" type="text"/>
Javascript:
var datepickr = (function() {
var datepickrs = [],
currentDate = new Date(),
date = {
current: {
year: function() {
return currentDate.getFullYear();
},
month: {
integer: function() {
return currentDate.getMonth();
},
string: function(full, months) {
var date = currentDate.getMonth();
return monthToStr(date, full, months);
minDate: currentDate;
}
},
day: function() {
return currentDate.getDate();
}
},
month: {
string: function(full, currentMonthView, months) {
var date = currentMonthView;
return monthToStr(date, full, months);
},
numDays: function(currentMonthView, currentYearView) {
/* checks to see if february is a leap year otherwise return the respective # of days */
return (currentMonthView == 1 && !(currentYearView & 3) && (currentYearView % 1e2 || !(currentYearView % 4e2))) ? 29 : daysInMonth[currentMonthView];
}
}
},
daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
buildCache = [],
handlers = {
calendarClick: function(e) {
if(e.target.className) {
switch(e.target.className) {
case 'prev-month':
case 'prevMonth':
this.currentMonthView--;
if(this.currentMonthView < 0) {
this.currentYearView--;
this.currentMonthView = 11;
}
rebuildCalendar.call(this);
break;
case 'next-month':
case 'nextMonth':
this.currentMonthView++;
if(this.currentMonthView > 11) {
this.currentYearView++;
this.currentMonthView = 0;
}
rebuildCalendar.call(this);
break;
case 'day':
this.element.value = formatDate(new Date(this.currentYearView, this.currentMonthView, e.target.innerHTML).getTime(), this.config);
this.close();
break;
}
}
},
documentClick: function(e) {
if(e.target != this.element && e.target != this.calendar) {
var parentNode = e.target.parentNode;
if(parentNode != this.calender) {
while(parentNode != this.calendar) {
parentNode = parentNode.parentNode;
if(parentNode == null) {
this.close();
break;
}
}
}
}
}
};
function formatDate(milliseconds, config) {
var formattedDate = '',
dateObj = new Date(milliseconds),
format = {
d: function() {
var day = format.j();
return (day < 10) ? '0' + day : day;
},
D: function() {
return config.weekdays[format.w()].substring(0, 3);
},
j: function() {
return dateObj.getDate();
},
l: function() {
return config.weekdays[format.w()];
},
S: function() {
return config.suffix[format.j()] || config.defaultSuffix;
},
w: function() {
return dateObj.getDay();
},
F: function() {
return monthToStr(format.n(), true, config.months);
},
m: function() {
var month = format.n() + 1;
return (month < 10) ? '0' + month : month;
},
M: function() {
return monthToStr(format.n(), false, config.months);
},
n: function() {
return dateObj.getMonth();
},
Y: function() {
return dateObj.getFullYear();
},
y: function() {
return format.Y().toString().substring(2, 4);
}
},
formatPieces = config.dateFormat.split('');
foreach(formatPieces, function(formatPiece, index) {
if(format[formatPiece] && formatPieces[index - 1] != '\\') {
formattedDate += format[formatPiece]();
} else {
if(formatPiece != '\\') {
formattedDate += formatPiece;
}
}
});
return formattedDate;
}
function foreach(items, callback) {
var i = 0, x = items.length;
for(i; i < x; i++) {
if(callback(items[i], i) === false) {
break;
}
}
}
function addEvent(element, eventType, callback) {
if(element.addEventListener) {
element.addEventListener(eventType, callback, false);
} else if(element.attachEvent) {
var fixedCallback = function(e) {
e = e || window.event;
e.preventDefault = (function(e) {
return function() { e.returnValue = false; }
})(e);
e.stopPropagation = (function(e) {
return function() { e.cancelBubble = true; }
})(e);
e.target = e.srcElement;
callback.call(element, e);
};
element.attachEvent('on' + eventType, fixedCallback);
}
}
function removeEvent(element, eventType, callback) {
if(element.removeEventListener) {
element.removeEventListener(eventType, callback, false);
} else if(element.detachEvent) {
element.detachEvent('on' + eventType, callback);
}
}
function buildNode(nodeName, attributes, content) {
var element;
if(!(nodeName in buildCache)) {
buildCache[nodeName] = document.createElement(nodeName);
}
element = buildCache[nodeName].cloneNode(false);
if(attributes != null) {
for(var attribute in attributes) {
element[attribute] = attributes[attribute];
}
}
if(content != null) {
if(typeof(content) == 'object') {
element.appendChild(content);
} else {
element.innerHTML = content;
}
}
return element;
}
function monthToStr(date, full, months) {
return ((full == true) ? months[date] : ((months[date].length > 3) ? months[date].substring(0, 3) : months[date]));
}
function isToday(day, currentMonthView, currentYearView) {
return day == date.current.day() && currentMonthView == date.current.month.integer() && currentYearView == date.current.year();
}
function buildWeekdays(weekdays) {
var weekdayHtml = document.createDocumentFragment();
foreach(weekdays, function(weekday) {
weekdayHtml.appendChild(buildNode('th', {}, weekday.substring(0, 2)));
});
return weekdayHtml;
}
function rebuildCalendar() {
while(this.calendarBody.hasChildNodes()){
this.calendarBody.removeChild(this.calendarBody.lastChild);
}
var firstOfMonth = new Date(this.currentYearView, this.currentMonthView, 1).getDay(),
numDays = date.month.numDays(this.currentMonthView, this.currentYearView);
this.currentMonth.innerHTML = date.month.string(this.config.fullCurrentMonth, this.currentMonthView, this.config.months) + ' ' + this.currentYearView;
this.calendarBody.appendChild(buildDays(firstOfMonth, numDays, this.currentMonthView, this.currentYearView));
}
function buildCurrentMonth(config, currentMonthView, currentYearView, months) {
return buildNode('span', { className: 'current-month' }, date.month.string(config.fullCurrentMonth, currentMonthView, months) + ' ' + currentYearView);
}
function buildMonths(config, currentMonthView, currentYearView) {
var months = buildNode('div', { className: 'months' }),
prevMonth = buildNode('span', { className: 'prev-month' }, buildNode('span', { className: 'prevMonth' }, '<')),
nextMonth = buildNode('span', { className: 'next-month' }, buildNode('span', { className: 'nextMonth' }, '>'));
months.appendChild(prevMonth);
months.appendChild(nextMonth);
return months;
}
function buildDays(firstOfMonth, numDays, currentMonthView, currentYearView) {
var calendarBody = document.createDocumentFragment(),
row = buildNode('tr'),
dayCount = 0, i;
/* print out previous month's "days" */
for(i = 1; i <= firstOfMonth; i++) {
row.appendChild(buildNode('td', null, ' '));
dayCount++;
}
for(i = 1; i <= numDays; i++) {
/* if we have reached the end of a week, wrap to the next line */
if(dayCount == 7) {
calendarBody.appendChild(row);
row = buildNode('tr');
dayCount = 0;
}
var todayClassName = isToday(i, currentMonthView, currentYearView) ? { className: 'today' } : null;
row.appendChild(buildNode('td', todayClassName, buildNode('span', { className: 'day' }, i)));
dayCount++;
}
/* if we haven't finished at the end of the week, start writing out the "days" for the next month */
for(i = 1; i <= (7 - dayCount); i++) {
row.appendChild(buildNode('td', null, ' '));
}
calendarBody.appendChild(row);
return calendarBody;
}
function buildCalendar() {
var firstOfMonth = new Date(this.currentYearView, this.currentMonthView, 1).getDay(),
numDays = date.month.numDays(this.currentMonthView, this.currentYearView),
self = this;
var inputLeft = inputTop = 0,
obj = this.element;
if(obj.offsetParent) {
do {
inputLeft += obj.offsetLeft;
inputTop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
var calendarContainer = buildNode('div', { className: 'calendar' });
calendarContainer.style.cssText = 'display: none; position: absolute; top: ' + (inputTop + this.element.offsetHeight) + 'px; left: ' + inputLeft + 'px; z-index: 100;';
this.currentMonth = buildCurrentMonth(this.config, this.currentMonthView, this.currentYearView, this.config.months)
var months = buildMonths(this.config, this.currentMonthView, this.currentYearView);
months.appendChild(this.currentMonth);
var calendar = buildNode('table', null, buildNode('thead', null, buildNode('tr', { className: 'weekdays' }, buildWeekdays(this.config.weekdays))));
this.calendarBody = buildNode('tbody');
this.calendarBody.appendChild(buildDays(firstOfMonth, numDays, this.currentMonthView, this.currentYearView));
calendar.appendChild(this.calendarBody);
calendarContainer.appendChild(months);
calendarContainer.appendChild(calendar);
document.body.appendChild(calendarContainer);
addEvent(calendarContainer, 'click', function(e) { handlers.calendarClick.call(self, e); });
return calendarContainer;
}
return function(elementId, userConfig) {
var self = this;
this.element = document.getElementById(elementId);
this.config = {
fullCurrentMonth: true,
dateFormat: 'F jS, Y',
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
suffix: { 1: 'st', 2: 'nd', 3: 'rd', 21: 'st', 22: 'nd', 23: 'rd', 31: 'st' },
defaultSuffix: 'th'
};
this.currentYearView = date.current.year();
this.currentMonthView = date.current.month.integer();
if(userConfig) {
for(var key in userConfig) {
if(this.config.hasOwnProperty(key)) {
this.config[key] = userConfig[key];
}
}
}
this.documentClick = function(e) { handlers.documentClick.call(self, e); }
this.open = function(e) {
addEvent(document, 'click', self.documentClick);
foreach(datepickrs, function(datepickr) {
if(datepickr != self) {
datepickr.close();
}
});
self.calendar.style.display = 'block';
}
this.close = function() {
removeEvent(document, 'click', self.documentClick);
self.calendar.style.display = 'none';
}
this.calendar = buildCalendar.call(this);
datepickrs.push(this);
if(this.element.nodeName == 'INPUT') {
addEvent(this.element, 'focus', this.open);
} else {
addEvent(this.element, 'click', this.open);
}
}
})();
I appreciate your help :)
-ShadowMinion

Custom function be called instead of getfullyear() in java script

I want my custom function be called instead of getfullyear() in java script how can I do this ? The point is to change a gregorian calendar to jallali in jomsocial.
for example when I write this
d=new Date(b.year,b.month,b.date+a);c.set("highlight",JalaliDate[d.getFullYear(),d.getMonth(),d.getDate()]
The result will be 2014/16/7, I want it to became 1393/6/25
This is the function that I want to be called
http://www.farsiweb.info/jalali/jalali.js
or
jQuery(function($){
$.datepicker.regional['fa'] = {
calendar: JalaliDate,
closeText: 'بستن',
prevText: 'قبل',
nextText: 'بعد',
currentText: 'امروز',
monthNames: ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'],
monthNamesShort: ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'],
dayNames: ['یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'],
dayNamesShort: ['یک', 'دو', 'سه', 'چهار', 'پنج', 'جمعه', 'شنبه'],
dayNamesMin: ['ی','د','س','چ','پ','ج','ش'],
weekHeader: 'ه',
dateFormat: 'dd/mm/yy',
firstDay: 6,
isRTL: true,
showMonthAfterYear: false,
yearSuffix: '',
calculateWeek: function(date) {
var checkDate = new JalaliDate(date.getFullYear(), date.getMonth(), date.getDate() + (date.getDay() || 7) - 3);
return Math.floor(Math.round((checkDate.getTime() - new JalaliDate(checkDate.getFullYear(), 0, 1).getTime()) / 86400000) / 7) + 1;
}};
$.datepicker.setDefaults($.datepicker.regional['fa']); });
function JalaliDate(p0, p1, p2) {
var gregorianDate;
var jalaliDate;
if (!isNaN(parseInt(p0)) && !isNaN(parseInt(p1)) && !isNaN(parseInt(p2))) {
var g = jalali_to_gregorian([parseInt(p0, 10), parseInt(p1, 10), parseInt(p2, 10)]);
setFullDate(new Date(g[0], g[1], g[2]));
} else {
setFullDate(p0);
}
function jalali_to_gregorian(d) {
var adjustDay = 0;
if(d[1]<0){
adjustDay = leap_persian(d[0]-1)? 30: 29;
d[1]++;
}
var gregorian = jd_to_gregorian(persian_to_jd(d[0], d[1] + 1, d[2])-adjustDay);
gregorian[1]--;
return gregorian;
}
function gregorian_to_jalali(d) {
var jalali = jd_to_persian(gregorian_to_jd(d[0], d[1] + 1, d[2]));
jalali[1]--;
return jalali;
}
function setFullDate(date) {
if (date && date.getGregorianDate) date = date.getGregorianDate();
gregorianDate = new Date(date);
gregorianDate.setHours(gregorianDate.getHours() > 12 ? gregorianDate.getHours() + 2 : 0)
if (!gregorianDate || gregorianDate == 'Invalid Date' || isNaN(gregorianDate || !gregorianDate.getDate())) {
gregorianDate = new Date();
}
jalaliDate = gregorian_to_jalali([
gregorianDate.getFullYear(),
gregorianDate.getMonth(),
gregorianDate.getDate()]);
return this;
}
this.getGregorianDate = function() { return gregorianDate; }
this.setFullDate = setFullDate;
this.setMonth = function(e) {
jalaliDate[1] = e;
var g = jalali_to_gregorian(jalaliDate);
gregorianDate = new Date(g[0], g[1], g[2]);
jalaliDate = gregorian_to_jalali([g[0], g[1], g[2]]);
}
this.setDate = function(e) {
jalaliDate[2] = e;
var g = jalali_to_gregorian(jalaliDate);
gregorianDate = new Date(g[0], g[1], g[2]);
jalaliDate = gregorian_to_jalali([g[0], g[1], g[2]]);
};
this.getFullYear = function() { return jalaliDate[0]; };
this.getMonth = function() { return jalaliDate[1]; };
this.getDate = function() { return jalaliDate[2]; };
this.toString = function() { return jalaliDate.join(',').toString(); };
this.getDay = function() { return gregorianDate.getDay(); };
this.getHours = function() { return gregorianDate.getHours(); };
this.getMinutes = function() { return gregorianDate.getMinutes(); };
this.getSeconds = function() { return gregorianDate.getSeconds(); };
this.getTime = function() { return gregorianDate.getTime(); };
this.getTimeZoneOffset = function() { return gregorianDate.getTimeZoneOffset(); };
this.getYear = function() { return jalaliDate[0] % 100; };
this.setHours = function(e) { gregorianDate.setHours(e) };
this.setMinutes = function(e) { gregorianDate.setMinutes(e) };
this.setSeconds = function(e) { gregorianDate.setSeconds(e) };
this.setMilliseconds = function(e) { gregorianDate.setMilliseconds(e) }; }
Thanks
If you are using http://www.farsiweb.info/jalali/jalali.js, try
function printJalali(year, month, day) {
var jalali = gregorian_to_jalali([year, month+1, day]);
return jalali[0] + "/" + jalali[1] + "/" + jalali[2];
}
var today = new Date();
alert(printJalali(today.getFullYear(), today.getMonth(), today.getDate()));

jQuery Datepicker close datepicker after selected date

HTML:
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="example1">
</div>
</div>
jQuery:
<script type="text/javascript">
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
I use bootstrap datepicker.
When I click to datepicker it opens and I select any date.
My question:
If I choose date from datepicker, I want to close datepicker popup.
Which event do i need to use in order to close datepicker on select date?
Edited:
I have found a solution
This works
$(document).mouseup(function (e) {
$('#example1').Close();
});
But this below does not work why ?
$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
Actually you don't need to replace this all (#Ben Rhouma Zied answere)....
There are 2 ways to do this. One is to use autoclose property, the other (alternativ) way is to use the on change property thats fired by the input when selecting a Date.
HTML
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
jQuery
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
this is all you have to do :)
HERE IS A FIDDLE to see whats happening.
Fiddleupdate on 13 of July 2016: CDN wasnt present anymore
According to your EDIT:
$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
Here you take the Input (that has no Close-Function) and create a Datepicker-Element. If the element changes you want to close it but you still try to close the Input (That has no close-function).
Binding a mouseup event to the document state may not be the best idea because you will fire all containing scripts on each click!
Thats it :)
EDIT: August 2017 (Added a StackOverFlowFiddle aka Snippet. Same as in Top of Post)
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
.hero-unit{
float: left;
width: 210px;
margin-right: 25px;
}
.hero-unit input{
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
EDIT: December 2018 Obviously Bootstrap-Datepicker doesnt work with jQuery 3.x see this to fix
This is my edited version : you just need to add an extra argument "autoClose".
example :
$('input[name="fieldName"]').datepicker({ autoClose: true});
also you can specify a close callback if you want. :)
replace datepicker.js with this:
!function( $ ) {
// Picker object
var Datepicker = function(element, options , closeCallBack){
this.element = $(element);
this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
this.closeCallback = closeCallBack || function(){};
this.picker = $(DPGlobal.template)
.appendTo('body')
.on({
click: $.proxy(this.click, this)//,
//mousedown: $.proxy(this.mousedown, this)
});
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
if (this.isInput) {
this.element.on({
focus: $.proxy(this.show, this),
//blur: $.proxy(this.hide, this),
keyup: $.proxy(this.update, this)
});
} else {
if (this.component){
this.component.on('click', $.proxy(this.show, this));
} else {
this.element.on('click', $.proxy(this.show, this));
}
}
this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
if (typeof this.minViewMode === 'string') {
switch (this.minViewMode) {
case 'months':
this.minViewMode = 1;
break;
case 'years':
this.minViewMode = 2;
break;
default:
this.minViewMode = 0;
break;
}
}
this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
if (typeof this.viewMode === 'string') {
switch (this.viewMode) {
case 'months':
this.viewMode = 1;
break;
case 'years':
this.viewMode = 2;
break;
default:
this.viewMode = 0;
break;
}
}
this.startViewMode = this.viewMode;
this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
this.onRender = options.onRender;
this.fillDow();
this.fillMonths();
this.update();
this.showMode();
};
Datepicker.prototype = {
constructor: Datepicker,
show: function(e) {
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
$(window).on('resize', $.proxy(this.place, this));
if (e ) {
e.stopPropagation();
e.preventDefault();
}
if (!this.isInput) {
}
var that = this;
$(document).on('mousedown', function(ev){
if ($(ev.target).closest('.datepicker').length == 0) {
that.hide();
}
});
this.element.trigger({
type: 'show',
date: this.date
});
},
hide: function(){
this.picker.hide();
$(window).off('resize', this.place);
this.viewMode = this.startViewMode;
this.showMode();
if (!this.isInput) {
$(document).off('mousedown', this.hide);
}
//this.set();
this.element.trigger({
type: 'hide',
date: this.date
});
},
set: function() {
var formated = DPGlobal.formatDate(this.date, this.format);
if (!this.isInput) {
if (this.component){
this.element.find('input').prop('value', formated);
}
this.element.data('date', formated);
} else {
this.element.prop('value', formated);
}
},
setValue: function(newDate) {
if (typeof newDate === 'string') {
this.date = DPGlobal.parseDate(newDate, this.format);
} else {
this.date = new Date(newDate);
}
this.set();
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
place: function(){
var offset = this.component ? this.component.offset() : this.element.offset();
this.picker.css({
top: offset.top + this.height,
left: offset.left
});
},
update: function(newDate){
this.date = DPGlobal.parseDate(
typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
this.format
);
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
fillDow: function(){
var dowCnt = this.weekStart;
var html = '<tr>';
while (dowCnt < this.weekStart + 7) {
html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '';
var i = 0
while (i < 12) {
html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').append(html);
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getFullYear(),
month = d.getMonth(),
currentDate = this.date.valueOf();
this.picker.find('.datepicker-days th:eq(1)')
.text(DPGlobal.dates.months[month]+' '+year);
var prevMonth = new Date(year, month-1, 28,0,0,0,0),
day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
prevMonth.setDate(day);
prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setDate(nextMonth.getDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName,
prevY,
prevM;
while(prevMonth.valueOf() < nextMonth) {zs
if (prevMonth.getDay() === this.weekStart) {
html.push('<tr>');
}
clsName = this.onRender(prevMonth);
prevY = prevMonth.getFullYear();
prevM = prevMonth.getMonth();
if ((prevM < month && prevY === year) || prevY < year) {
clsName += ' old';
} else if ((prevM > month && prevY === year) || prevY > year) {
clsName += ' new';
}
if (prevMonth.valueOf() === currentDate) {
clsName += ' active';
}
html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
if (prevMonth.getDay() === this.weekEnd) {
html.push('</tr>');
}
prevMonth.setDate(prevMonth.getDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date.getFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear === year) {
months.eq(this.date.getMonth()).addClass('active');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
click: function(e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length === 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
this.viewDate,
this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) +
DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
);
this.fill();
this.set();
break;
}
break;
case 'span':
if (target.is('.month')) {
var month = target.parent().find('span').index(target);
this.viewDate.setMonth(month);
} else {
var year = parseInt(target.text(), 10)||0;
this.viewDate.setFullYear(year);
}
if (this.viewMode !== 0) {
this.date = new Date(this.viewDate);
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
}
this.showMode(-1);
this.fill();
this.set();
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
var day = parseInt(target.text(), 10)||1;
var month = this.viewDate.getMonth();
if (target.is('.old')) {
month -= 1;
} else if (target.is('.new')) {
month += 1;
}
var year = this.viewDate.getFullYear();
this.date = new Date(year, month, day,0,0,0,0);
this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
this.fill();
this.set();
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
if(this.autoClose === true){
this.hide();
this.closeCallback();
}
}
break;
}
}
},
mousedown: function(e){
e.stopPropagation();
e.preventDefault();
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
}
};
$.fn.datepicker = function ( option, val ) {
return this.each(function () {
var $this = $(this);
var datePicker = $this.data('datepicker');
var options = typeof option === 'object' && option;
if (!datePicker) {
if (typeof val === 'function')
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
else{
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
}
}
if (typeof option === 'string') datePicker[option](val);
});
};
$.fn.datepicker.defaults = {
onRender: function(date) {
return '';
}
};
$.fn.datepicker.Constructor = Datepicker;
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
dates:{
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
today: "Aujourd'hui",
clear: "Effacer",
weekStart: 1,
format: "dd/mm/yyyy"
},
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
},
parseFormat: function(format){
var separator = format.match(/[.\/\-\s].*?/),
parts = format.split(/\W+/);
if (!separator || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separator: separator, parts: parts};
},
parseDate: function(date, format) {
var parts = date.split(format.separator),
date = new Date(),
val;
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
if (parts.length === format.parts.length) {
var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
val = parseInt(parts[i], 10)||1;
switch(format.parts[i]) {
case 'dd':
case 'd':
day = val;
date.setDate(val);
break;
case 'mm':
case 'm':
month = val - 1;
date.setMonth(val - 1);
break;
case 'yy':
year = 2000 + val;
date.setFullYear(2000 + val);
break;
case 'yyyy':
year = val;
date.setFullYear(val);
break;
}
}
date = new Date(year, month, day, 0 ,0 ,0);
}
return date;
},
formatDate: function(date, format){
var val = {
d: date.getDate(),
m: date.getMonth() + 1,
yy: date.getFullYear().toString().substring(2),
yyyy: date.getFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [];
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
date.push(val[format.parts[i]]);
}
return date.join(format.separator);
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">‹</th>'+
'<th colspan="5" class="switch"></th>'+
'<th class="next">›</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'</div>';
}( window.jQuery );
There is another code that's works for me (jQuery).
$(".datepicker").datepicker({
format: "dd/mm/yyyy",
autoHide: true
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />
Date: <input type="text" readonly="true" class="datepicker">
Answer above did not work for me on Chrome. The change event was been fired after I clicked out of the field somewhere, which did not help because the datepicker window is also closed too when you click out of the field.
I did use this code and it worked pretty well. You can place it after calling .datepicker();
HTML
<input type="text" class="datepicker-input" placeholder="click to show datepicker" />
JavaScript
$(".datepicker-input").each(function() {
$(this).datepicker();
});
$(".datepicker-input").click(function() {
$(".datepicker-days .day").click(function() {
$('.datepicker').hide();
});
});
Just add this option to Datepicker component:
forceParse: false
Example:
$('.datepicker').datepicker({
format: 'mm/dd/yyyy',
defaultDate: 'now',
forceParse: false,
endDate: "today"
});

Categories

Resources