custom calendar using javascript - javascript

I want to create a calendar with date picker using java script of my own design without using any j-query library. I found one code and i created calendar with that but i am not to find how to five next and previous month button in calendar and i want to highlight the current date. I also need to click on date to perform certain operations. How do it do it?? Please help me.
This is my code
// these are labels for the days of the week
cal_days_labels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
// these are human-readable month name labels, in order
cal_months_labels = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'];
// these are the days of the week for each month, in order
cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// this is the current date
cal_current_date = new Date();
function Calendar(month, year) {
this.month = (isNaN(month) || month == null) ? cal_current_date.getMonth() : month;
this.year = (isNaN(year) || year == null) ? cal_current_date.getFullYear() : year;
this.html = '';
}
Calendar.prototype.generateHTML = function () {
// get first day of month
var firstDay = new Date(this.year, this.month, 1);
var startingDay = firstDay.getDay();
// find number of days in month
var monthLength = cal_days_in_month[this.month];
// compensate for leap year
if (this.month == 1) { // February only!
if ((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0) {
monthLength = 29;
}
}
// do the header
var monthName = cal_months_labels[this.month]
var html = '<table class="calendar-table">';
html += '<tr><th colspan="7">';
html += monthName + " " + this.year;
html += '</th></tr>';
html += '<tr class="calendar-header">';
for (var i = 0; i <= 6; i++) {
html += '<td class="calendar-header-day">';
html += cal_days_labels[i];
html += '</td>';
}
html += '</tr><tr>';
// fill in the days
var day = 1;
// this loop is for is weeks (rows)
for (var i = 0; i < 9; i++) {
// this loop is for weekdays (cells)
for (var j = 0; j <= 6; j++) {
html += '<td class="calendar-day">';
if (day <= monthLength && (i > 0 || j >= startingDay)) {
html += day;
day++;
}
html += '</td>';
}
// stop making rows if we've run out of days
if (day > monthLength) {
break;
} else {
html += '</tr><tr>';
}
}
html += '</tr></table>';
this.html = html;
}
Calendar.prototype.getHTML = function () {
return this.html;
}
this is my script to get calendar:
<script type="text/javascript">
var cal = new Calendar();
cal.generateHTML();
document.write(cal.getHTML());
</script>

var curMonth = parseInt(document.getElementById("ContentPlaceHolder1_lblMonth").innerText);
document.getElementById("ContentPlaceHolder1_lblMonthDDD").innerText = convertMonth_ddToDDD(curMonth);
previous();
function previous() {
var curMonth = parseInt(document.getElementById("ContentPlaceHolder1_lblMonth").innerText);
var curYear = parseInt(document.getElementById("ContentPlaceHolder1_lblYear").innerText)
var prevMonth = getPreviousMonth(curMonth, curYear);
var prevYear = getPreviousYear(curMonth, curYear);
document.getElementById("ContentPlaceHolder1_lblMonth").innerText = prevMonth;
document.getElementById("ContentPlaceHolder1_lblMonthDDD").innerText = convertMonth_ddToDDD(prevMonth);
document.getElementById("ContentPlaceHolder1_lblYear").innerText = prevYear;
createCalenderTable(prevMonth, prevYear);
return false;
}
function next() {
var curMonth = parseInt(document.getElementById("ContentPlaceHolder1_lblMonth").innerText);
var curYear = parseInt(document.getElementById("ContentPlaceHolder1_lblYear").innerText)
var nextMonth = getNextMonth(curMonth, curYear);
var nextYear = getNextYear(curMonth, curYear);
document.getElementById("ContentPlaceHolder1_lblMonth").innerText = nextMonth;
document.getElementById("ContentPlaceHolder1_lblMonthDDD").innerText = convertMonth_ddToDDD(nextMonth);
document.getElementById("ContentPlaceHolder1_lblYear").innerText = nextYear;
createCalenderTable(nextMonth, nextYear);
return false;
}
function getPreviousMonth(curMonth, curYear) {
//alert("current: "+ curMonth +" "+curYear);
var prevMonth;
//for month: ...3, 2, 1, 12, 11, 10...
if (curMonth == 1) {
prevMonth = 12;
} else {
prevMonth = curMonth - 1;
}
//alert(prevMonth + " " + prevYear);
return prevMonth;
}
function getNextMonth(curMonth, curYear) {
//alert("current: "+ curMonth +" "+curYear);
var nextMonth;
//for month: ...3, 2, 1, 12, 11, 10...
if (curMonth == 12) {
nextMonth = 1;
} else {
nextMonth = curMonth + 1;
}
//alert(prevMonth + " " + prevYear);
return nextMonth;
}
function getPreviousYear(curMonth, curYear) {
//alert("current: " + curMonth + " " + curYear);
//var prevMonth;
var prevYear;
//for prev year if month==12 the decrement
if (curMonth == 1) {
prevYear = curYear - 1;
} else {
prevYear = curYear;
}
return prevYear;
}
function getNextYear(curMonth, curYear) {
//alert("current: " + curMonth + " " + curYear);
//var prevMonth;
var nextYear;
//for prev year if month==12 the decrement
if (curMonth == 12) {
nextYear = curYear + 1;
} else {
nextYear = curYear;
}
return nextYear;
}
function isThisLeapYear(year) {
//temporary taken static
if (year % 4 == 0 || year % 100 == 100) {
return true;
} else {
return false;
}
}
function createCalenderTable(monthNo, year) {
var totalDays = getTotalDaysForThisMonth(monthNo, year);
var firstDateDayNo = getMonthFirstDate_DayNo(monthNo, year);
var tableHeader = "<table style='box-shadow:3px 3px 24px 1px gray' cellPadding='10' border='1px solid black'>";
tableHeader += "<tr style='background-color:lightgray;'><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th>" + trEnd;
var trStart = "<tr>";
var trEnd = "</tr>";
var tableEnd = "</table>";
var datesInRow = "";
var rowContent = "";
var i = 1;
//alert(totalDays);
while (i <= totalDays) {
//week
rowContent += trStart;
for (var j = 0; j <= 6 && i <= totalDays; j++, i++) {
while (firstDateDayNo > 0) {
rowContent += "<td id='0'></td>";
firstDateDayNo--;
j++;
}
rowContent += "<td id='" + i + "' onclick='return setThisSelectedDateToTextBox(" + i + ");'>" + i + "</td>";
}
rowContent += trEnd;
//i+=7;
}
//var tableOuter = "<table><tr><td>"+"</td></tr></table>";
document.getElementById("divCal").innerHTML = tableHeader + rowContent + tableEnd;
}
function getMonthFirstDate_DayNo(monthNo, year) {
var dt = new Date(year, monthNo - 1, 1);
// alert(dt+"----"+dt.getDay());
return dt.getDay();
}
function getTotalDaysForThisMonth(monthNo, year) {
switch (monthNo) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
break;
case 4:
case 6:
case 9:
case 11:
return 30;
break;
//for february
case 2:
if (isThisLeapYear(year)) {
return 29
} else {
return 28;
}
default:
return 99;
break;
}
}
function convertMonth_ddToDDD(thisMonth) {
var month = thisMonth;
switch (month) {
case 1:
return "January";
break;
case 2:
return "February";
break;
case 3:
return "March";
break;
case 4:
return "April";
break;
case 5:
return "May";
break;
case 6:
return "June";
break;
case 7:
return "July";
break;
case 8:
return "August";
break;
case 9:
return "September";
break;
case 10:
return "October";
break;
case 11:
return "November";
break;
case 12:
return "December";
break;
default:
return "Unknown";
break;
}
}
function convertDayNumber_to_dayName(dayNo) {
switch (dayNo) {
case 0:
return "Sunday";
break;
case 1:
return "Monday";
break;
case 2:
return "Tuesday";
break;
case 3:
return "Wednesday";
break;
case 4:
return "Thursday";
break;
case 5:
return "Friday";
break;
case 6:
return "Saturday";
break;
default:
return "UnknownDay";
break;
}
}
function setThisSelectedDateToTextBox(selectedDate) {
var curMonth = document.getElementById("ContentPlaceHolder1_lblMonth").innerText;
var curYear = document.getElementById("ContentPlaceHolder1_lblYear").innerText;
document.getElementById("txtDate").value = selectedDate + "/" + curMonth + "/" + curYear;
//alert(selectedDate + "/" + curMonth + "/" + curYear);
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
string dateStart = txtStartDate.Text;
string dateEnd = txtEndDate.Text;
DateTime startDate = DateTime.ParseExact(dateStart, "MM/dd/yyyy",null);
DateTime endDate = DateTime.ParseExact(dateEnd, "MM/dd/yyyy",null);
ArrayList dayResult = new ArrayList();
if (rbtType1.Checked)
{
int selectedDayOpt = Convert.ToInt32(ddlEvery.SelectedValue);
int selectedCalOpt = Convert.ToInt32(ddlCalDates.SelectedValue);
while(endDate > startDate)
{
dayResult.Add(startDate);
switch(selectedCalOpt)
{
case 1:
startDate = startDate.AddDays(1 * selectedDayOpt);
break;
case 2:
startDate = startDate.AddDays(7 * selectedDayOpt);
break;
case 3:
startDate = startDate.AddMonths(1 * selectedDayOpt);
break;
case 4:
startDate = startDate.AddYears(1 * selectedDayOpt);
break;
default:
break;
}
}
}
else
{
string selectedDayName = Convert.ToString(ddDay.SelectedItem);
int selectedWeek = Convert.ToInt32(ddNthWeek.SelectedValue);
int selectedMonthDiff = Convert.ToInt32(ddMonthDifference.SelectedValue);
while(endDate > startDate)
{
string dayName = startDate.ToString("dddd");
if(dayName.ToUpper()== selectedDayName.ToUpper())
{
int weekNo = Convert.ToInt32(startDate.Day) % 7 == 0 ? Convert.ToInt32(startDate.Day) / 7 : (Convert.ToInt32(startDate.Day) / 7) + 1;
if (weekNo == selectedWeek)
{
dayResult.Add(startDate);
startDate = startDate.AddDays((selectedMonthDiff * 28) - weekNo);
}
}
startDate = startDate.AddDays(1);
}
}
gvDates.DataSource = dayResult;
gvDates.DataBind();
}
}
}

Related

How to build up a list with html tags in a javascript function

I have written code to display the date (month, day, day nr, and year) with javascript and placed it in a ul.
my question is how to build up a li with html tags (so that i can place breaks) in a javascript function because now if i would for example do the following
var output = "<li>" + month_full[monthFull] + "<br/>" + weekDay[day] + "</li>";
return output;
it will output exactly how its shown -> http://gyazo.com/5a67f3dbd7db07254bd38d58116aac7c
you can horizontally scroll through my months. now i would like to build it up like so: http://gyazo.com/adb760c912691a7ce26b1cc40d89d1df
to check my jsfiddle to see what i have now: https://jsfiddle.net/GY22/vqfk8yLL/2/
my javascript code is the following:
<script>
// Get today's current date.
var now = new Date();
console.log(now);
// Calculates the number of the week
var weekNumber = ((now.getDate()<10) ? "0" : "")+ now.getDate();
console.log("The current week number is: " + weekNumber);
// Array list of months.
var month_full = new Array(12);
month_full[0] = "January";
month_full[1] = "February";
month_full[2] = "March";
month_full[3] = "April";
month_full[4] = "May";
month_full[5] = "June";
month_full[6] = "July";
month_full[7] = "August";
month_full[8] = "September";
month_full[9] = "October";
month_full[10] = "November";
month_full[11] = "December";
//console.log(month[3]);
var weekDay = new Array(7);
weekDay[0]= "Su";
weekDay[1] = "Mo";
weekDay[2] = "Tu";
weekDay[3] = "We";
weekDay[4] = "Th";
weekDay[5] = "Fr";
weekDay[6] = "Sa";
function weekNr_Month(date){
var month = date.getUTCMonth();
return month[month];
}
function formatDate(date) {
var month = date.getUTCMonth() +1;
var dayNumber = date.getUTCDate();
var year = date.getUTCFullYear();
var day = date.getUTCDay();
var monthFull = date.getUTCMonth();
return month_full[monthFull] + " " + weekDay[day] + ": " + dayNumber + "-" + month + "-" + year + "; ";
}
console.log(formatDate(new Date()));
var today
function addListItem(){
var createListItem = document.createElement("li");
var outputListItem = document.createTextNode(today);
createListItem.appendChild(outputListItem);
var createUl = document.getElementsByTagName("ul");
createUl[0].appendChild(createListItem);
}
// loop starting from may up untill for months from the set date
for (var i = 1; i < 122; i++){
today = formatDate(new Date(2015, 05, i));
//document.write(today + "<br />");
addListItem();
}
document.getElementById('timeline').
getElementsByTagName('li')[(new Date()).getDate() + 1].className += ' currentDate';
</script>
That is because you are creating a text node instead of html content.
Try this:
var createListItem = document.createElement("li");
createListItem.innerHTML = today;

View only two weeks in the month using Calenderio

I am trying to display a two week view using Calenderio. So for example it should display 4/19/2015 - 5/2/2015, not the entire month of April. I am confused as to where in the JS I have to modify it to display only two weeks.
Here is the JS:
function($, window, undefined) {
'use strict';
$.Calendario = function(options, element) {
this.$el = $(element);
this._init(options);
};
// the options
$.Calendario.defaults = {
/*
you can also pass:
month : initialize calendar with this month (1-12). Default is today.
year : initialize calendar with this year. Default is today.
caldata : initial data/content for the calendar.
caldata format:
{
'MM-DD-YYYY' : 'HTML Content',
'MM-DD-YYYY' : 'HTML Content',
...
}
*/
weeks: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
weekabbrs: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthabbrs: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
displayWeekAbbr: false, // choose between values in options.weeks or options.weekabbrs
displayMonthAbbr: false, // choose between values in options.months or options.monthabbrs
startIn: 0, // left most day in the calendar (0 - Sunday, 1 - Monday, ... , 6 - Saturday)
events: 'click',
fillEmpty: true,
feedParser: './feed/',
zone: '00:00', // Ex: IST zone time is '+05:30' by default it is GMT, Sign is important.
checkUpdate: true //Check if any new version of Calendario is released (Details will be in the browser console)
};
$.Calendario.prototype = {
_init: function(options) {
// options
this.VERSION = '3.2.0';
this.UNIQUE = '%{unique}%'; //UNIQUE helps us differentiate your js from others and help us keep a track of run time.
this.options = $.extend(true, {}, $.Calendario.defaults, options);
this.today = new Date();
this.month = (isNaN(this.options.month) || this.options.month === null) ? this.today.getMonth() : this.options.month - 1;
this.year = (isNaN(this.options.year) || this.options.year === null) ? this.today.getFullYear() : this.options.year;
this.caldata = this._processCaldata(this.options.caldata);
// if hover is passed as an event then throw error if jQuery is 1.9 or above 1.9, because, hover psuedo name isn't supported
if (parseFloat($().jquery) >= 1.9 && this.options.events.indexOf('hover') != -1)
this.logError('\'hover\' psuedo-name is not supported' + ' in jQuery 1.9+. Use \'mouseenter\' \'mouseleave\' events instead.');
this.options.events = this.options.events.split(',');
this.options.zone = this.options.zone.charAt(0) != '+' && this.options.zone.charAt(0) != '-' ? '+' + this.options.zone : this.options.zone;
this._generateTemplate(true);
this._initEvents();
},
_processCaldataObj: function(val, key) {
if (typeof val !== 'object') val = {
content: val,
startTime: '00:00',
endTime: '23:59',
allDay: true
};
if (!val.content) this.logError('Content is missing in date ' + key);
if (val.startTime && !val.endTime) val.endTime = parseInt(val.startTime.split(':')[0]) + 1 + ':' + val.startTime.split(':')[1];
if (!val.startTime && !val.endTime) val = $.extend({}, val, {
startTime: '00:00',
endTime: '23:59',
allDay: true
});
if (val.startTime && val.endTime && val.allDay === undefined) val.allDay = false;
if (/^\d{2}-DD-\d{4}/.test(key) || /^\d{2}-DD-YYYY/.test(key)) {
var det = /^(\d{2})-DD-(\d{4})/.exec(key) || /^(\d{2})-DD-YYYY/.exec(key),
chkDate;
if (det.length == 3) chkDate = new Date(det[2], det[1], 0);
else if (det.length == 2) chkDate = new Date(this.year, det[1], 0)
if (!val.startDate) val.startDate = 1;
if (!val.endDate && chkDate.getDate() != 1) val.endDate = chkDate.getDate();
if (!val.endDate && chkDate.getDate() == 1 && det.length == 3) val.endDate = chkDate.getDate();
}
return val;
},
_processCaldata: function(caldata) {
var self = this;
caldata = caldata || {};
$.each(caldata, function(key, val) {
if (/^\d{2}-\d{2}-\d{4}/.test(key) || /^\d{2}-\d{2}-YYYY/.test(key) || /^\d{2}-DD-YYYY/.test(key) || /^MM-\d{2}-YYYY/.test(key) ||
/^\d{2}-DD-YYYY/.test(key) || /^MM-\d{2}-\d{4}/.test(key) || /^\d{2}-DD-\d{4}/.test(key) || key == 'TODAY') {} else
self.logError(key + ' is an Invalid Date. Date should not contain spaces, should be separated by \'-\' and should be in the ' +
'format \'MM-DD-YYYY\'. That ain\'t that difficult!');
if (Array.isArray(val)) {
$.each(val, function(i, c) {
val[i] = self._processCaldataObj(c, key);
});
caldata[key] = val;
} else {
caldata[key] = self._processCaldataObj(val, key);
}
});
return caldata;
},
_propDate: function($cell, event) {
var idx = $cell.index(),
data = {
allDay: [],
content: [],
endTime: [],
startTime: []
},
dateProp = {
day: $cell.children('span.fc-date').text(),
month: this.month + 1,
monthname: this.options.displayMonthAbbr ? this.options.monthabbrs[this.month] : this.options.months[this.month],
year: this.year,
weekday: idx + this.options.startIn,
weekdayname: this.options.weeks[(idx == 6 ? 0 : idx + this.options.startIn)]
};
$cell.children('div.fc-calendar-events').children('div.fc-calendar-event').each(function(i, e) {
var $html = $('<div>' + $(e).html() + '</div>');
data.startTime[i] = new Date($html.find('time.fc-starttime').attr('datetime'));
data.endTime[i] = new Date($html.find('time.fc-endtime').attr('datetime'));
data.allDay[i] = $html.find('time.fc-allday').attr('datetime') === 'true' ? true : false;
$html.find('time').remove();
data.content[i] = $html.html();
});
if (dateProp.day) this.options[event]($cell, data, dateProp);
},
_initEvents: function() {
var self = this,
event = [],
calendarioEventNameFormat = [];
for (var i = 0; i < self.options.events.length; i++) {
event[i] = self.options.events[i].toLowerCase().trim();
calendarioEventNameFormat[i] = 'onDay' + event[i].charAt(0).toUpperCase() + event[i].slice(1);
if (this.options[calendarioEventNameFormat[i]] === undefined)
this.options[calendarioEventNameFormat[i]] = function($el, $content, dateProperties) {
return false;
};
this.$el.on(event[i] + '.calendario', 'div.fc-row > div', function(e) {
if (e.type == 'mouseenter' || e.type == 'mouseleave') e.type = $.inArray(e.type, event) == -1 ? 'hover' : e.type;
self._propDate($(this), calendarioEventNameFormat[$.inArray(e.type, event)]);
});
}
this.$el.on('shown.calendar.calendario', function(e, instance) {
// If check update set to true, then contact calendario's update servers for details. We didn't want to slow down your code. So we
// check after the calendar is rendered.
if (instance && instance.options.checkUpdate) self._checkUpdate();
});
// newday trigger. This trigger is exactly triggered at 00:00 hours the next day with an uncertainty of 6ms.
this.$el.delay(new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate() + 1, 0, 0, 0) - new Date().getTime())
.queue(function() {
self.today = new Date();
if (self.today.getMonth() == self.month || self.today.getMonth() + 1 == self.month) self._generateTemplate(true);
self.$el.trigger($.Event('newday.calendar.calendario'));
});
},
_checkUpdate: function() {
var self = this;
$.getScript("https://raw.githubusercontent.com/codrops/Calendario/master/js/update.js")
.done(function(script, textStatus) {
if (calendario.current != self.version() && parseFloat(calendario.current) >= parseFloat(self.version()))
console.info(calendario.msg);
})
.fail(function(jqxhr, settings, exception) {
console.error(exception);
});
},
// Calendar logic based on http://jszen.blogspot.pt/2007/03/how-to-build-simple-calendar-with.html
_generateTemplate: function(firstRun, callback) {
var head = this._getHead(),
body = this._getBody(),
rowClass;
switch (this.rowTotal) {
case 2:
rowClass = 'fc-two-rows';
break;
case 3:
rowClass = 'fc-three-rows';
break;
case 4:
rowClass = 'fc-four-rows';
break;
case 5:
rowClass = 'fc-five-rows';
break;
case 6:
rowClass = 'fc-six-rows';
break;
}
this.$cal = $('<div class="fc-calendar ' + rowClass + '">').append(head, body);
this.$el.find('div.fc-calendar').remove().end().append(this.$cal);
this.$el.find('.fc-emptydate').parent().css({
'background': 'transparent',
'cursor': 'default'
});
if (!firstRun) this.$el.trigger($.Event('shown.calendario'));
if (callback) callback.call();
},
_getHead: function() {
var html = '<div class="fc-head">';
for (var i = 0; i <= 6; i++) {
var pos = i + this.options.startIn,
j = pos > 6 ? pos - 6 - 1 : pos;
html += '<div>' + (this.options.displayWeekAbbr ? this.options.weekabbrs[j] : this.options.weeks[j]) + '</div>';
}
return html + '</div>';
},
_parseDataToDay: function(data, day, other) {
var content = '';
if (!other) {
if (Array.isArray(data)) content = this._convertDayArray(data, day);
else content = this._wrapDay(data, day, true);
} else {
if (!Array.isArray(data)) data = [data];
for (var i = 0; i < data.length; i++) {
if (this.month != 1 && (day >= data[i].startDate) && (day <= data[i].endDate)) content += this._wrapDay(data[i], day, true);
else if (this.month == 1 && (day >= data[i].startDate)) {
if (data[i].endDate && (day <= data[i].endDate)) content += this._wrapDay(data[i], day, true);
else if (!data[i].endDate) content += this._wrapDay(data[i], day, true);
}
}
}
return content;
},
_toDateTime: function(time, day, start) {
var zoneH = parseInt(this.options.zone.split(':')[0]),
zoneM = parseInt(this.options.zone.charAt(0) + this.options.zone.split(':')[1]),
hour = parseInt(time.split(':')[0]) - zoneH,
minutes = parseInt(time.split(':')[1]) - zoneM,
d = new Date(Date.UTC(this.year, this.month, day, hour, minutes, 0, 0));
if (start) {
var hStart = parseInt(start.split(':')[0]) - zoneH,
mStart = parseInt(start.split(':')[1]) - zoneM;
if (d.getTime() - new Date(Date.UTC(this.year, this.month, day, hStart, mStart, 0, 0)).getTime() < 0)
d = new Date(Date.UTC(this.year, this.month, day + 1, hour, minutes, 0, 0));
}
return d.toISOString();
},
_timeHtml: function(day, date) {
var content = day.content;
content += '<time class="fc-allday" datetime="' + day.allDay + '"></time>';
content += '<time class="fc-starttime" datetime="' + this._toDateTime(day.startTime, date) + '">' + day.startTime + '</time>';
content += '<time class="fc-endtime" datetime="' + this._toDateTime(day.endTime, date, day.startTime) + '">' + day.endTime + '</time>';
return content;
},
_wrapDay: function(day, date, wrap) {
if (date) {
if (wrap) return '<div class="fc-calendar-event">' + this._timeHtml(day, date) + '</div>';
else return this._timeHtml(day, date);
} else return '<div class="fc-calendar-event">' + day + '</div>';
},
_convertDayArray: function(day, date) {
var wrap_days = []
for (var i = 0; i < day.length; i++) {
wrap_days[i] = this._wrapDay(day[i], date, false);
}
return this._wrapDay(wrap_days.join('</div><div class="fc-calendar-event">'));
},
_getBody: function() {
var d = new Date(this.year, this.month + 1, 0),
monthLength = d.getDate(), // number of days in the month
firstDay = new Date(this.year, d.getMonth(), 1),
pMonthLength = new Date(this.year, this.month, 0).getDate();
// day of the week
this.startingDay = firstDay.getDay();
var html = '<div class="fc-body"><div class="fc-row">',
day = 1; // fill in the days
for (var i = 0; i < 7; i++) { // this loop is for weeks (rows)
for (var j = 0; j <= 6; j++) { // this loop is for weekdays (cells)
var pos = this.startingDay - this.options.startIn,
p = pos < 0 ? 6 + pos + 1 : pos,
inner = '',
today = this.month === this.today.getMonth() && this.year === this.today.getFullYear() && day === this.today.getDate(),
past = this.year < this.today.getFullYear() || this.month < this.today.getMonth() && this.year === this.today.getFullYear() ||
this.month === this.today.getMonth() && this.year === this.today.getFullYear() && day < this.today.getDate(),
content = '';
if (this.options.fillEmpty && (j < p || i > 0)) {
if (day > monthLength) {
inner = '<span class="fc-date fc-emptydate">' + (day - monthLength) + '</span><span class="fc-weekday">';
++day;
} else if (day == 1) {
inner = '<span class="fc-date fc-emptydate">' + (pMonthLength - p + 1) + '</span><span class="fc-weekday">';
++pMonthLength;
}
inner += this.options.weekabbrs[j + this.options.startIn > 6 ? j + this.options.startIn - 6 - 1 : j + this.options.startIn] + '</span>';
}
if (day <= monthLength && (i > 0 || j >= p)) {
inner = '<span class="fc-date">' + day + '</span><span class="fc-weekday">' + this.options.weekabbrs[j +
this.options.startIn > 6 ? j + this.options.startIn - 6 - 1 : j + this.options.startIn] + '</span>';
var strdate = (this.month + 1 < 10 ? '0' + (this.month + 1) : this.month + 1) + '-' + (day < 10 ? '0' + day : day) + '-' + this.year,
dayData = this.caldata[strdate],
strdateyear = (this.month + 1 < 10 ? '0' + (this.month + 1) : this.month + 1) + '-' + (day < 10 ? '0' + day : day) + '-YYYY',
dayDataYear = this.caldata[strdateyear],
strdatemonth = 'MM-' + (day < 10 ? '0' + day : day) + '-' + this.year,
dayDataMonth = this.caldata[strdatemonth],
strdatemonthyear = 'MM' + '-' + (day < 10 ? '0' + day : day) + '-YYYY',
dayDataMonthYear = this.caldata[strdatemonthyear],
strdatemonthlyyear = (this.month + 1 < 10 ? '0' + (this.month + 1) : this.month + 1) + '-DD-' + this.year,
dayDataMonthlyYear = this.caldata[strdatemonthlyyear],
strdatemonthly = (this.month + 1 < 10 ? '0' + (this.month + 1) : this.month + 1) + '-DD-YYYY',
dayDataMonthly = this.caldata[strdatemonthly];
if (today && this.caldata.TODAY) content += this._parseDataToDay(this.caldata.TODAY, day);
if (dayData) content += this._parseDataToDay(dayData, day);
if (dayDataMonth) content += this._parseDataToDay(dayDataMonth, day);
if (dayDataMonthlyYear) content += this._parseDataToDay(dayDataMonthlyYear, day, true);
if (dayDataMonthly) content += this._parseDataToDay(dayDataMonthly, day, true);
if (dayDataMonthYear) content += this._parseDataToDay(dayDataMonthYear, day);
if (dayDataYear) content += this._parseDataToDay(dayDataYear, day);
if (content !== '') inner += '<div class="fc-calendar-events">' + content + '</div>';
++day;
} else {
today = false;
}
var cellClasses = today ? 'fc-today ' : '';
if (past) cellClasses += 'fc-past ';
else cellClasses += 'fc-future ';
if (content !== '') cellClasses += 'fc-content';
html += (cellClasses !== '' ? '<div class="' + cellClasses.trim() + '">' : '<div>') + inner + '</div>';
}
if (day > monthLength) { // stop making rows if we've run out of days
this.rowTotal = i + 1;
break;
} else {
html += '</div><div class="fc-row">';
}
}
return html + '</div></div>';
},
_move: function(period, dir, callback) {
if (dir === 'previous') {
if (period === 'month') {
this.year = this.month > 0 ? this.year : --this.year;
this.month = this.month > 0 ? --this.month : 11;
} else if (period === 'year') this.year = --this.year;
} else if (dir === 'next') {
if (period === 'month') {
this.year = this.month < 11 ? this.year : ++this.year;
this.month = this.month < 11 ? ++this.month : 0;
} else if (period === 'year') this.year = ++this.year;
}
this._generateTemplate(false, callback);
},
/*************************
***** PUBLIC METHODS *****
**************************/
option: function(option, value) {
if (value) this.options[option] = value;
else return this.options[option];
},
getYear: function() {
return this.year;
},
getMonth: function() {
return this.month + 1;
},
getMonthName: function() {
return this.options.displayMonthAbbr ? this.options.monthabbrs[this.month] : this.options.months[this.month];
},
// gets the cell's content div associated to a day of the current displayed month
// day : 1 - [28||29||30||31]
getCell: function(day) {
var row = Math.floor((day + this.startingDay - this.options.startIn - 1) / 7),
pos = day + this.startingDay - this.options.startIn - (row * 7) - 1;
return this.$cal.find('div.fc-body').children('div.fc-row').eq(row).children('div').eq(pos);
},
setData: function(caldata, clear) {
caldata = this._processCaldata(caldata);
if (clear) this.caldata = caldata;
else $.extend(this.caldata, caldata);
this._generateTemplate(false);
},
// goes to today's month/year
gotoNow: function(callback) {
this.month = this.today.getMonth();
this.year = this.today.getFullYear();
this._generateTemplate(false, callback);
},
// goes to month/year
gotoMonth: function(month, year, callback) {
this.month = month - 1;
this.year = year;
this._generateTemplate(false, callback);
},
gotoPreviousMonth: function(callback) {
this._move('month', 'previous', callback);
},
gotoPreviousYear: function(callback) {
this._move('year', 'previous', callback);
},
gotoNextMonth: function(callback) {
this._move('month', 'next', callback);
},
gotoNextYear: function(callback) {
this._move('year', 'next', callback);
},
feed: function(callback) {
var self = this;
$.post(self.options.feedParser, {
dates: this.caldata
})
.always(function(data) {
if (callback) callback.call(this, JSON.parse(data).hevent);
});
},
version: function() {
return this.VERSION;
}
};
var logError = function(message) {
throw new Error(message);
};
$.fn.calendario = function(options) {
var instance = $.data(this, 'calendario');
if (typeof options === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function() {
if (!instance) {
logError("Cannot call methods on calendario prior to initialization; Attempted to call method '" + options + "'");
return;
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
logError("No such method '" + options + "' for calendario instance.");
}
instance[options].apply(instance, args);
});
} else {
this.each(function() {
if (instance) instance._init();
else instance = $.data(this, 'calendario', new $.Calendario(options, this));
});
}
instance.$el.trigger($.Event('shown.calendar.calendario'), [instance]);
return instance;
};
})(jQuery, window);
I'm not sure you can yet - Developer of the version you posted, better version available at https://github.com/deviprsd21/Calendario

How to clear div content onclick? [duplicate]

This question already has answers here:
How do I clear the content of a div using JavaScript? [closed]
(2 answers)
Closed 7 years ago.
I'm making a calendar purely from Javascript, but when then previous and next months are shown current content is still present. It should replace the div content. Also, current date should be the only one with red font displayed.
<html>
<head><script>
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var monthName = getMonthName(month);
var time = now.toLocaleTimeString();
var date = now.getDate();
now = null;
var calElem = document.getElementById("cal");
function febDays(year) {
if (year % 4 == 0) {
return 29;
} else {
return 28;
}
}
function getDays(month, year) {
var days = new Array(12);
days[0] = 31;
days[1] = febDays(year);
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
days[7] = 31;
days[8] = 30;
days[9] = 31;
days[10] = 30;
days[11] = 31;
return days[month];
}
function getMonthName(month) {
var mn = new Array(12);
mn[0] = "January";
mn[1] = "February";
mn[2] = "March";
mn[3] = "April";
mn[4] = "May";
mn[5] = "June";
mn[6] = "July";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function monthName(month) {
var mn = new Array(12);
mn[0] = "Jan";
mn[1] = "Feb";
mn[2] = "Mar";
mn[3] = "Apr";
mn[4] = "May";
mn[5] = "Jun";
mn[6] = "Jul";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function setCal() {
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
function previousMonth() {
document.getElementById('cal').innerHTML = "";
month--;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "January"){
year--;
month = 11;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function nextMonth() {
document.getElementById('cal').innerHTML = "";
month++;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "December"){
year++;
month = 0;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function drawCal(startDay, lastDate, date, monthName, year, month) {
var headerHeight = 50;
var border = 2;
var cellspacing = 4;
var headerSize = "+3";
var colWidth = 60;
var dayCellHeight = 25;
var cellHeight = 40;
var todayColor = "red";
var text = "";
text += '<div id="cal">';
text += '<TABLE BORDER=' + border + ' CELLSPACING=' + cellspacing + '>';
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>';
text += '<FONT SIZE=' + headerSize + '>';
text += monthName + ' ' + year;
text += '</FONT>';
text += '</TH>';
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>';
var closeCol = '</TD>';
var weekDay = new Array(7);
weekDay[0] = "Sunday";
weekDay[1] = "Monday";
weekDay[2] = "Tuesday";
weekDay[3] = "Wednesday";
weekDay[4] = "Thursday";
weekDay[5] = "Friday";
weekDay[6] = "Saturday";
text += '<TR ALIGN="center" VALIGN="center">';
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol;
}
text += '</TR>';
var digit = 1;
var curCell = 1;
for (var row = 1; row <= Math.ceil((lastDate + startDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top">';
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break;
if (curCell < startDay) {
text += '<TD></TD>';
curCell++;
} else {
if (digit == date) {
text += '<TD HEIGHT=' + cellHeight + '>';
text += '<FONT COLOR="' + todayColor + '">';
text += digit + " ";
text += '</FONT>';
text += '</TD>';
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>';
digit++;
}
}
text += '</TR>';
}
text += '</TABLE>';
text += '</CENTER>';
text += '</div>';
text += '<button onclick="previousMonth()"><</button>';
text += '<button onclick="nextMonth()">></button>';
document.write(text);
}
</script></head>
<body onload="setCal()">
</body>
</html>
I think it will be better if you can use a container element and set its content rather than to use document.write()
<html>
<head><script>
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var monthName = getMonthName(month);
var time = now.toLocaleTimeString();
var date = now.getDate();
now = null;
var calElem = document.getElementById("cal");
function febDays(year) {
if (year % 4 == 0) {
return 29;
} else {
return 28;
}
}
function getDays(month, year) {
var days = new Array(12);
days[0] = 31;
days[1] = febDays(year);
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
days[7] = 31;
days[8] = 30;
days[9] = 31;
days[10] = 30;
days[11] = 31;
return days[month];
}
function getMonthName(month) {
var mn = new Array(12);
mn[0] = "January";
mn[1] = "February";
mn[2] = "March";
mn[3] = "April";
mn[4] = "May";
mn[5] = "June";
mn[6] = "July";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function monthName(month) {
var mn = new Array(12);
mn[0] = "Jan";
mn[1] = "Feb";
mn[2] = "Mar";
mn[3] = "Apr";
mn[4] = "May";
mn[5] = "Jun";
mn[6] = "Jul";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function setCal() {
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
function previousMonth() {
document.getElementById('cal').innerHTML = "";
month--;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "January"){
year--;
month = 11;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function nextMonth() {
document.getElementById('cal').innerHTML = "";
month++;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "December"){
year++;
month = 0;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function drawCal(startDay, lastDate, date, monthName, year, month) {
var headerHeight = 50;
var border = 2;
var cellspacing = 4;
var headerSize = "+3";
var colWidth = 60;
var dayCellHeight = 25;
var cellHeight = 40;
var todayColor = "red";
var text = "";
text += '<div id="cal">';
text += '<TABLE BORDER=' + border + ' CELLSPACING=' + cellspacing + '>';
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>';
text += '<FONT SIZE=' + headerSize + '>';
text += monthName + ' ' + year;
text += '</FONT>';
text += '</TH>';
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>';
var closeCol = '</TD>';
var weekDay = new Array(7);
weekDay[0] = "Sunday";
weekDay[1] = "Monday";
weekDay[2] = "Tuesday";
weekDay[3] = "Wednesday";
weekDay[4] = "Thursday";
weekDay[5] = "Friday";
weekDay[6] = "Saturday";
text += '<TR ALIGN="center" VALIGN="center">';
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol;
}
text += '</TR>';
var digit = 1;
var curCell = 1;
for (var row = 1; row <= Math.ceil((lastDate + startDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top">';
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break;
if (curCell < startDay) {
text += '<TD></TD>';
curCell++;
} else {
if (digit == date) {
text += '<TD HEIGHT=' + cellHeight + '>';
text += '<FONT COLOR="' + todayColor + '">';
text += digit + " ";
text += '</FONT>';
text += '</TD>';
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>';
digit++;
}
}
text += '</TR>';
}
text += '</TABLE>';
text += '</CENTER>';
text += '</div>';
text += '<button onclick="previousMonth()"><</button>';
text += '<button onclick="nextMonth()">></button>';
document.getElementById('calc').innerHTML=text;
}
</script></head>
<body onload="setCal()">
<div id="calc"></div>
</body>
</html>
if you want to clear any HTML element you would just
DO NOT use document.write() it clears the whole page.
It's the document.write() It always stays there no matter what. Try not to use document.write()
use createElement('div') instead. It's much more clean, you can keep track of the elements, and they're static, unless you want them to change. everything is under your control.
document.getElementById('Clear_This_Div_id').innerHTML = '';
This will usually clear the element
Without changing much of the other part of your code, you can just change the
document.write(text);
to
document.getElementsByTagName('body')[0].innerHTML = text;
This will clear off the previous content before putting the new one, since you are putting in the body every time.

JavaScript array sort not working in default Android browser

I have a problem with the function listed below. On my PC this code is working perfectly, and on Chrome on my mobile phone too. However, when I run this code in the default Android browser the result is that the first 4 elements of the sorted array are not what they are supposed to be;
Element 1: 0
Element 2: 128
Element 3: 256
Element 4: 384
Now I am wondering why this is the case, up until where the array is sorted the values gathered are fine, after that, they are incorrect...
According to this link it should be compatible with the default Android browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Browser_compatibility
function sendWeekProgram() {
//Get all the info to send
var weekProgramData;
//Check if the week program is enabled
if($("#vacationMode").prop('checked') === false) {
weekProgramData = '<week_program state="on">';
}else {
weekProgramData = '<week_program state="off">';
}
//For each day get the switches
for(i = 0; i < 7; i++) {
//Set the day name
switch(i) {
case 0:
dayName = "Monday";
break;
case 1:
dayName = "Tuesday";
break;
case 2:
dayName = "Wednesday";
break;
case 3:
dayName = "Thursday";
break;
case 4:
dayName = "Friday";
break;
case 5:
dayName = "Saturday";
break;
case 6:
dayName = "Sunday";
break;
}
//Add the day to the query
weekProgramData = weekProgramData + '<day name="' + dayName + '">';
//Create an array
var arraySwitches = [];
//Put all day switches in an array
for(j = 0; j < 5; j++) {
//Check if the switch is on or off
if(($("#daySwitch" + dayName + (j + 1)).hasClass("dayOverViewTextActive") === false) || ($("#nightSwitch" + dayName + (j + 1)).hasClass("dayOverViewTextActive") === false)) {
arraySwitches[j] = {type: 'day', state: 'off', value: parseInt($("#daySwitch" + dayName + (j + 1)).text().replace(":", ""))};
}else {
arraySwitches[j] = {type: 'day', state: 'on', value: parseInt($("#daySwitch" + dayName + (j + 1)).text().replace(":", ""))};
}
}
//Put all night switches in an array
for(j = 5; j < 10; j++) {
//Check if the switch is on or off
if(($("#daySwitch" + dayName + (j-4)).hasClass("dayOverViewTextActive") === false) || ($("#nightSwitch" + dayName + (j-4)).hasClass("dayOverViewTextActive") === false)) {
arraySwitches[j] = {type: 'night', state: 'off', value: parseInt($("#nightSwitch" + dayName + (j-4)).text().replace(":", ""))};
}else {
arraySwitches[j] = {type: 'night', state: 'on', value: parseInt($("#nightSwitch" + dayName + (j-4)).text().replace(":", ""))};
}
}
//Sort the array
arraySwitches.sort(function(a, b) {
return a.value
- b.value;
});
//For each element in the array, add it to the weekProgramData
for(k = 0; k < 10; k++) {
//Add leading zeroes
arrayValue = arraySwitches[k].value.toString();
while(arrayValue.length < 4) {
arrayValue = "0" + arrayValue;
}
//First convert the integer back to the time
time = arrayValue.substr(0,2) + ':' + arrayValue.substr(2);
//Add value to weekprogram
weekProgramData = weekProgramData + '<switch type="' + arraySwitches[k].type + '" state="' + arraySwitches[k].state + '">' + time + '</switch>';
}
//Add the closing tag of the day
weekProgramData = weekProgramData + '</day>';
}
//Add the closing tag of the week program
weekProgramData = weekProgramData + '</week_program>';
//Send the info
putInfo("weekProgram", weekProgramData);
}

Cant get what's the issue with Datepicker?

I'm using smarty template engine. I'm using datepicker js plugin. My HTML code is as follows:
<tr>
<td valign="middle" align="right"><b>From Date </b> : </td>
<td align="left" > <input type="text" style="width:100px;" class="inputfield" name="from_date" id="from_date" value="{$from_date}" maxlength="10"/></td>
<td valign="middle" align="right"><b>To Date </b> : </td>
<td> <input type="text" style="width:100px;" class="inputfield" name="to_date" id="to_date" value="{$to_date}" maxlength="10"/></td>
</tr>
The jQuery function code is as below :
{literal}
<script language="javascript" type="application/javascript">
$(function() {
$( "#from_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
$(function() {
$( "#to_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
$(document).ready(function() {
$("#questions_listing").tablesorter({
widgets:['zebra'],
// sort on the fourth column and first column, order asc
sortList: [[1,0]]
});
});
$(".submit_form").click(function(e) {
var result = validateDate();
if(!result)
return false;
else
document.questions_filter.submit();
});
</script>
{/literal}
The datepicker.js file is as follows:
/* $(function() {
$( "#cal_from_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
$( "#cal_to_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});*/
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";
var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var defaultDateSeparator = "/"; // common values would be "/" or "."
var defaultDateFormat = "dmy" // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
var targetDateField = document.getElementsByName (dateFieldName).item(0);
if (!displayBelowThisObject)
displayBelowThisObject = targetDateField;
if (dtSep)
dateSeparator = dtSep;
else
dateSeparator = defaultDateSeparator;
if (dtFormat)
dateFormat = dtFormat;
else
dateFormat = defaultDateFormat;
var x = displayBelowThisObject.offsetLeft;
var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
var parent = displayBelowThisObject;
while (parent.offsetParent) {
parent = parent.offsetParent;
x += parent.offsetLeft;
y += parent.offsetTop ;
}
drawDatePicker(targetDateField, x, y);
}
function drawDatePicker(targetDateField, x, y)
{
var dt = getFieldDate(targetDateField.value );
if (!document.getElementById(datePickerDivID)) {
// don't use innerHTML to update the body, because it can cause global variables
// that are currently pointing to objects on the page to have bad references
//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
var newNode = document.createElement("div");
newNode.setAttribute("id", datePickerDivID);
newNode.setAttribute("class", "dpDiv");
newNode.setAttribute("style", "visibility: hidden;");
document.body.appendChild(newNode);
}
// move the datepicker div to the proper x,y coordinate and toggle the visiblity
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.position = "absolute";
pickerDiv.style.left = x + "px";
pickerDiv.style.top = y + "px";
pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
pickerDiv.style.zIndex = 10000;
// draw the datepicker table
refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}
function refreshDatePicker(dateFieldName, year, month, day)
{
var thisDay = new Date();
if ((month >= 0) && (year > 0)) {
thisDay = new Date(year, month, 1);
} else {
day = thisDay.getDate();
thisDay.setDate(1);
}
var crlf = "\r\n";
var TABLE = "<table cols=7 class='dpTable'>" + crlf;
var xTABLE = "</table>" + crlf;
var TR = "<tr class='dpTR'>";
var TR_title = "<tr class='dpTitleTR'>";
var TR_days = "<tr class='dpDayTR'>";
var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
var xTR = "</tr>" + crlf;
var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";
var TD_title = "<td colspan=5 class='dpTitleTD'>";
var TD_buttons = "<td class='dpButtonTD'>";
var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
var TD_days = "<td class='dpDayTD'>";
var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' "; // leave this tag open, because we'll be adding an onClick event
var xTD = "</td>" + crlf;
var DIV_title = "<div class='dpTitleText'>";
var DIV_selected = "<div class='dpDayHighlight'>";
var xDIV = "</div>";
// start generating the code for the calendar table
var html = TABLE;
// this is the title bar, which displays the month and the buttons to
// go back to a previous month or forward to the next month
html += TR_title;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "<") + xTD;
html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, ">") + xTD;
html += xTR;
// this is the row that indicates which day of the week we're on
html += TR_days;
for(i = 0; i < dayArrayShort.length; i++)
html += TD_days + dayArrayShort[i] + xTD;
html += xTR;
// now we'll start populating the table with days of the month
html += TR;
// first, the leading blanks
for (i = 0; i < thisDay.getDay(); i++)
html += TD + " " + xTD;
// now, the days of the month
do {
dayNum = thisDay.getDate();
TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
if (dayNum == day)
html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
else
html += TD + TD_onclick + dayNum + xTD;
// if this is a Saturday, start a new row
if (thisDay.getDay() == 6)
html += xTR + TR;
// increment the day
thisDay.setDate(thisDay.getDate() + 1);
} while (thisDay.getDate() > 1)
// fill in any trailing blanks
if (thisDay.getDay() > 0) {
for (i = 6; i > thisDay.getDay(); i--)
html += TD + " " + xTD;
}
html += xTR;
// add a button to allow the user to easily return to today, or close the calendar
var today = new Date();
var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
html += TR_todaybutton + TD_todaybutton;
html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>this month</button> ";
html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
html += xTD + xTR;
// and finally, close the table
html += xTABLE;
document.getElementById(datePickerDivID).innerHTML = html;
// add an "iFrame shim" to allow the datepicker to display above selection lists
adjustiFrame();
}
/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
var newMonth = (dateVal.getMonth () + adjust) % 12;
var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
if (newMonth < 0) {
newMonth += 12;
newYear += -1;
}
return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}
/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
var dayString = "00" + dateVal.getDate();
var monthString = "00" + (dateVal.getMonth()+1);
dayString = dayString.substring(dayString.length - 2);
monthString = monthString.substring(monthString.length - 2);
switch (dateFormat) {
case "dmy" :
return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
case "ymd" :
return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
case "mdy" :
default :
return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
}
}
/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
var dateVal;
var dArray;
var d, m, y;
try {
dArray = splitDateString(dateString);
if (dArray) {
switch (dateFormat) {
case "dmy" :
d = parseInt(dArray[0], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[2], 10);
break;
case "ymd" :
d = parseInt(dArray[2], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[0], 10);
break;
case "mdy" :
default :
d = parseInt(dArray[1], 10);
m = parseInt(dArray[0], 10) - 1;
y = parseInt(dArray[2], 10);
break;
}
dateVal = new Date(y, m, d);
} else if (dateString) {
dateVal = new Date(dateString);
} else {
dateVal = new Date();
}
} catch(e) {
dateVal = new Date();
}
return dateVal;
}
function splitDateString(dateString)
{
var dArray;
if (dateString.indexOf("/") >= 0)
dArray = dateString.split("/");
else if (dateString.indexOf(".") >= 0)
dArray = dateString.split(".");
else if (dateString.indexOf("-") >= 0)
dArray = dateString.split("-");
else if (dateString.indexOf("\\") >= 0)
dArray = dateString.split("\\");
else
dArray = false;
return dArray;
}
function updateDateField(dateFieldName, dateString)
{
var targetDateField = document.getElementsByName (dateFieldName).item(0);
if (dateString)
targetDateField.value = dateString;
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.visibility = "hidden";
pickerDiv.style.display = "none";
adjustiFrame();
targetDateField.focus();
// after the datepicker has closed, optionally run a user-defined function called
// datePickerClosed, passing the field that was just updated as a parameter
// (note that this will only run if the user actually selected a date from the datepicker)
if ((dateString) && (typeof(datePickerClosed) == "function"))
datePickerClosed(targetDateField);
}
function adjustiFrame(pickerDiv, iFrameDiv)
{
// we know that Opera doesn't like something about this, so if we
// think we're using Opera, don't even try
var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
if (is_opera)
return;
// put a try/catch block around the whole thing, just in case
try {
if (!document.getElementById(iFrameDivID)) {
var newNode = document.createElement("iFrame");
newNode.setAttribute("id", iFrameDivID);
newNode.setAttribute("src", "javascript:false;");
newNode.setAttribute("scrolling", "no");
newNode.setAttribute ("frameborder", "0");
document.body.appendChild(newNode);
}
if (!pickerDiv)
pickerDiv = document.getElementById(datePickerDivID);
if (!iFrameDiv)
iFrameDiv = document.getElementById(iFrameDivID);
try {
iFrameDiv.style.position = "absolute";
iFrameDiv.style.width = pickerDiv.offsetWidth;
iFrameDiv.style.height = pickerDiv.offsetHeight ;
iFrameDiv.style.top = pickerDiv.style.top;
iFrameDiv.style.left = pickerDiv.style.left;
iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
iFrameDiv.style.visibility = pickerDiv.style.visibility ;
iFrameDiv.style.display = pickerDiv.style.display;
} catch(e) {
}
} catch (ee) {
}
}
When I tested in firbug it is giving me the error TypeError: $(...).datepicker is not a function
I've included the files reuired i.e. jquery1.9.1 and datepicker .js, but still it's not working. Can anyone help me to resolve this issue?
Your code is just working perfectly! Check out this.
You just missed to include jquery-ui
Try including : <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> in you <head> tag.
UPDATE: The fiddle is by #Safiuddin

Categories