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

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()));

Related

loop available dates, select one of them and fill the input box

I am trying to fill in the input that is normally filled by a js code inside the html:
<input type="text" readonly="" class="form-control-input app_date validate" style="width: 260px;" id="app_date" name="app_date" placeholder="YYYY-MM-DD" onchange="this.form.submit();showLoader();" value="" autocomplete="off">
js code got from html
import re
html = """
<script type="text/javascript">
var dt4 = '2019-03-07';
var blocked_dates = ["20-03-2019","01-01-1970","28-03-2019","29-03-2019","20-03-2019","01-01-1970","28-03-2019","29-03-2019"];
var available_dates = ["07-03-2019","08-03-2019","11-03-2019","12-03-2019","13-03-2019","14-03-2019","15-03-2019","18-03-2019","19-03-2019","21-03-2019","22-03-2019","25-03-2019","26-03-2019","27-03-2019"];
var fullCapicity_dates = [];
var offDates_dates = ["09-03-2019","10-03-2019","16-03-2019","17-03-2019","20-03-2019","23-03-2019","24-03-2019","28-03-2019","29-03-2019","30-03-2019","31-03-2019"];
var allowArray = [1];
</script>
"""
i successfully captured the available dates :
date_list = re.findall(r'var\s*available_dates\s*=\s*\[[^\]]+', html)
if date_list:
for av_date in re.findall(r"\"[0-9\-]+\"",date_list[0]) :
print(av_date.replace('"',''))
Break
else : print("no available dates")
output :
07-03-2019 08-03-2019 11-03-2019 12-03-2019 13-03-2019 14-03-2019
15-03-2019 18-03-2019 19-03-2019 21-03-2019 22-03-2019 25-03-2019
26-03-2019 27-03-2019
I don't know how to loop the availables dates , select one of them and fill the input and continue the py script. if no available dates keep refreshing the current page until available dates are found. i am confused is it a while loop, a while true or if ?
full js code
<script type="text/javascript">
var today = new Date();
var dd = today.getDate()+1;
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = yyyy+'-'+mm+'-'+dd;
function formatDate(rawDate) {
var day = ("0" + rawDate.getDate()).slice(-2);
var month = ("0" + (rawDate.getMonth() + 1)).slice(-2);
return (day)+ "-" + (month)+ "-" +rawDate.getFullYear() ;
}
$(document).ready(function() {
var dt1 = '2019-03-06';
var checkService = 'Normal';
$('#dateOfBirth').datepicker({
format: "yyyy-mm-dd",
endDate: new Date(dt1),
startDate: '-100y',
autoclose: true,
startView: 2
});
$('#pptIssueDate').datepicker({
format: "yyyy-mm-dd",
endDate: new Date(dt1),
startDate: '-100y',
autoclose: true,
startView: 2
});
$('#pptExpiryDate').datepicker({
format: "yyyy-mm-dd",
startDate: new Date(dt1),
autoclose: true,
startView: 2
});
var dt4 = '2019-03-07';
var blocked_dates = ["20-03-2019","01-01-1970","28-03-2019","29-03-2019","20-03-2019","01-01-1970","28-03-2019","29-03-2019"];
var available_dates = ["07-03-2019","08-03-2019","11-03-2019","12-03-2019","13-03-2019","14-03-2019","15-03-2019","18-03-2019","19-03-2019","21-03-2019","22-03-2019","25-03-2019","26-03-2019","27-03-2019"];
var fullCapicity_dates = [];
var offDates_dates = ["09-03-2019","10-03-2019","16-03-2019","17-03-2019","20-03-2019","23-03-2019","24-03-2019","28-03-2019","29-03-2019","30-03-2019","31-03-2019"];
var allowArray = [1];
if(checkService == 'Normal')
{
/*if((jQuery.inArray(2, allowArray)!='-1') || (jQuery.inArray(3, allowArray)!='-1'))
{
var classFull = 'fullcapspecial';
var tooltipTitle = ' ';
var backDatetitle = 'Not Allowed';
}else{
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}*/
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}else{
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}
$('.app_date').datepicker({
language: "en",
Default: true,
format: "yyyy-mm-dd",
startDate: new Date(dt4),
endDate: '2019-03-31',
autoclose: true,
forceParse:true,
startView: 0,
beforeShowDay: function(date){
var formattedDate = formatDate(date);
if ($.inArray(formattedDate.toString(), blocked_dates) != -1){
return {
enabled : false,
classes: 'inactiveClass',
tooltip: 'Holiday'
};
}
if ($.inArray(formattedDate.toString(), available_dates) != -1){
return {
enabled : true,
classes: 'activeClass',
tooltip: 'Book'
};
}
if ($.inArray(formattedDate.toString(), fullCapicity_dates) != -1){
return {
enabled : false,
classes: classFull,
tooltip: tooltipTitle
};
}
if ($.inArray(formattedDate.toString(), offDates_dates) != -1){
return {
enabled : false,
classes: 'offday',
tooltip: 'Off Day'
};
}
return {
enabled : false,
tooltip: backDatetitle
};
return;
}
});
/*====== CALL POP FOR PL/PT IN NORMAL CASE=======*/
if(checkService == 'Normal')
{
if((jQuery.inArray(2, allowArray)!='-1') || (jQuery.inArray(3, allowArray)!='-1'))
{
/*$(document).on('click', '.fullcap,.fullcapspecial', function () {
$(".datepicker").hide();
$('.popupBG').show();
$('#IDBodyPanel').show();
});
$(".popupCloseIcon").click(function() {
$(".popupBG").hide();
$("#IDBodyPanel").hide();
});
$('input[type=radio][name=serviceChange]').change(function() {
if (this.value == 'Premium') {
$("#premiumService").prop('value', 'GO FOR PREMIUM');
}
else if (this.value == 'Prime') {
$("#premiumService").prop('value', 'GO FOR PRIME TIME');
}
});*/
}
}
/*====== CALL POP FOR PL/PT IN NORMAL CASE=======*/
var eventhandler = function(e) {
e.preventDefault();
}
if (checkService == 'Premium' || checkService == 'Prime') {
$('input[name="vasId[]"]:checked').each(function() {
$("#vasId"+this.value).bind('click', eventhandler);
});
}
if (checkService != 'Premium')
{
$(document).on('click', '.chkbox', function () {
if($(this).val() == 1)
{
if($(this).is(":checked")){
//$("#vasId6").prop('checked', true);
//$("#vasId6").bind('click', eventhandler);
}else{
//$("#vasId6").prop('checked', false);
//$("#vasId6").unbind('click', eventhandler);
}
}
});
}
});
</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

Input Calendar jumping to next input

I'm using this Calendar, and "i'm forced to use it" and i'm wondering if you could help me sorting out a small issue i'm having.
Calendar: http://www.bulgaria-web-developers.com/projects/javascript/calendar/
I have 2 input fields that this calendar is on,
<input type="text" id="cr_date_from" />
<input type="text" id="cr_date_to" />
And after selecting the date in "date_from" i need it to jump to "date_to" and have the same date as selected in the date_from field. As this will not cause confusion when people are selecting a date months ahead in time, and not to scroll all the way to that date in the date_to as well...
I've tried researching on this for a while now without luck, so i'm hoping you guys are able to help me out..
Appreciate all help on this!
Here is also the javascript for those interested...
bindSearch: function () {
var self = this,
dateFrom = new Calendar({
element: "cr_date_from",
//dateFormat: "Y-m-d",
dateFormat: self.opts.dateFormat,
monthNamesFull: self.opts.monthNamesFull,
dayNames: self.opts.dayNames,
disablePast: true,
months: 3,
onSelect: function () {
reCalc.call(self);
}
}),
dateTo = new Calendar({
element: "cr_date_to",
//dateFormat: "Y-m-d",
dateFormat: self.opts.dateFormat,
monthNamesFull: self.opts.monthNamesFull,
dayNames: self.opts.dayNames,
disablePast: true,
months: 3,
onSelect: function () {
reCalc.call(self);
}
}),
lnkFrom = document.getElementById("crDateFrom"),
lnkTo = document.getElementById("crDateTo"),
btnQuote = document.getElementById("crBtnQuote"),
btnMap = document.getElementById("crBtnMap"),
sameLoc = document.getElementById("cr_same_location"),
returnLoc = document.getElementById("crReturnBox");
self.elFrom = document.getElementById("cr_date_from");
self.elTo = document.getElementById("cr_date_to");
self.elHFrom = document.getElementById("cr_hour_from");
self.elMFrom = document.getElementById("cr_minutes_from");
self.elHTo = document.getElementById("cr_hour_to");
self.elMTo = document.getElementById("cr_minutes_to");
function reCalc() {
var from = Date.parseExact(this.elFrom.value, dateFormat(self.opts.dateFormat, 'datejs')).getTime() + (parseInt(this.elHFrom.value, 10) * 3600000) + (parseInt(this.elMFrom.value, 10) * 60000),
to = Date.parseExact(this.elTo.value, dateFormat(self.opts.dateFormat, 'datejs')).getTime() + (parseInt(this.elHTo.value, 10) * 3600000) + (parseInt(this.elMTo.value, 10) * 60000),
nd = document.getElementById("crNumDays"),
days;
if (from !== null && to !== null) {
days = Math.ceil((to - from) / 86400000);
if (days > 0) {
nd.lastChild.innerHTML = days;
nd.style.display = "";
} else {
nd.style.display = "none";
}
} else {
nd.style.display = "none";
}
}
if (lnkFrom) {
lnkFrom.onclick = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
dateFrom.isOpen ? dateFrom.close() : dateFrom.open();
return false;
};
}
if (lnkTo) {
lnkTo.onclick = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
dateTo.isOpen ? dateTo.close() : dateTo.open();
return false;
};
}
if (btnMap) {
btnMap.onclick = function (e) {
self.overlayMap.open();
if (e && e.preventDefault) {
e.preventDefault();
}
return false;
}
}
if (sameLoc && returnLoc) {
function bindLoc(el) {
if (this.checked) {
el.style.display = "none";
} else {
el.style.display = "";
}
}
sameLoc.onchange = function () {
bindLoc.call(this, returnLoc);
};
sameLoc.onclick = function () {
bindLoc.call(this, returnLoc);
};
}
if (btnQuote) {
btnQuote.onclick = function () {
this.disabled = true;
if (!self.validateSearch(this)) {
this.disabled = false;
return;
}
self.passed.first = true;
self.loadCars.apply(self, [JABB.Utils.serialize(document.getElementById("crFormSearch"))]);
};
}
},

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

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.

Categories

Resources