Calendar displays 24 hour clock and I need 12 hour clock - javascript

I have this e-calendar JavaScript code that is displaying 24hour clock format. How do you get it to change to 12 hour clock? Forgive the chopped up code, I had to delete some of it to create the post.
I have posted the code below:
(function ($) {
var eCalendar = function (options, object) {
// Initializing global variables
var adDay = new Date().getDate();
var adMonth = new Date().getMonth();
var adYear = new Date().getFullYear();
var dDay = adDay;
var dMonth = adMonth;
var dYear = adYear;
var instance = object;
var settings = $.extend({}, $.fn.eCalendar.defaults, options);
function print() {
loadEvents();
var dWeekDayOfMonthStart = new Date(dYear, dMonth, 1).getDay();
var dLastDayOfMonth = new Date(dYear, dMonth + 1, 0).getDate();
var dLastDayOfPreviousMonth = new Date(dYear, dMonth + 1, 0).getDate() - dWeekDayOfMonthStart + 1;
var cBody = $('<div/>').addClass('c-grid');
var cEvents = $('<div/>').addClass('c-event-grid');
var cEventsBody = $('<div/>').addClass('c-event-body');
cEvents.append($('<div/>').addClass('c-event-title c-pad-top').html(settings.eventTitle));
cEvents.append(cEventsBody);
var cNext = $('<div/>').addClass('c-next c-grid-title c-pad-top');
var cMonth = $('<div/>').addClass('c-month c-grid-title c-pad-top');
var cPrevious = $('<div/>').addClass('c-previous c-grid-title c-pad-top');
cPrevious.html(settings.textArrows.previous);
cMonth.html(settings.months[dMonth] + ' ' + dYear);
cNext.html(settings.textArrows.next);
cPrevious.on('mouseover', mouseOver).on('mouseleave', mouseLeave).on('click', previousMonth);
cNext.on('mouseover', mouseOver).on('mouseleave', mouseLeave).on('click', nextMonth);
cBody.append(cPrevious);
cBody.append(cMonth);
cBody.append(cNext);
for (var i = 0; i < settings.weekDays.length; i++) {
var cWeekDay = $('<div/>').addClass('c-week-day c-pad-top');
cWeekDay.html(settings.weekDays[i]);
cBody.append(cWeekDay);
}
var day = 1;
var dayOfNextMonth = 1;
for (var i = 0; i < 42; i++) {
var cDay = $('<div/>');
if (i < dWeekDayOfMonthStart) {
cDay.addClass('c-day-previous-month c-pad-top');
cDay.html(dLastDayOfPreviousMonth++);
} else if (day <= dLastDayOfMonth) {
cDay.addClass('c-day c-pad-top');
if (day == dDay && adMonth == dMonth && adYear == dYear) {
cDay.addClass('c-today');
}
for (var j = 0; j < settings.events.length; j++) {
var d = settings.events[j].datetime;
if (d.getDate() == day && (d.getMonth() - 1) == dMonth && d.getFullYear() == dYear) {
cDay.addClass('c-event').attr('data-event-day', d.getDate());
cDay.on('mouseover', mouseOverEvent).on('mouseleave', mouseLeaveEvent);
}
}
cDay.html(day++);
} else {
cDay.addClass('c-day-next-month c-pad-top');
cDay.html(dayOfNextMonth++);
}
cBody.append(cDay);
}
var eventList = $('<div/>').addClass('c-event-list');
for (var i = 0; i < settings.events.length; i++) {
var d = settings.events[i].datetime;
if ((d.getMonth() - 1) == dMonth && d.getFullYear() == dYear) {
var date = lpad(d.getDate(), 2) + '/' + lpad(d.getMonth(), 2) + ' ' + lpad(d.getHours(), 2) + ':' + lpad(d.getMinutes(), 2);
var item = $('<div/>').addClass('c-event-item');
var title = $('<div/>').addClass('title').html(date + ' ' + settings.events[i].title + '<br />');
var description = $('<div/>').addClass('description').html(settings.events[i].description + '<br />');
item.attr('data-event-day', d.getDate());
item.on('mouseover', mouseOverItem).on('mouseleave', mouseLeaveItem);
item.append(title).append(description);
eventList.append(item);
}
}
$(instance).addClass('calendar');
cEventsBody.append(eventList);
$(instance).html(cBody).append(cEvents);
}
return print();
}
$.fn.eCalendar = function (oInit) {
return this.each(function () {
return eCalendar(oInit, $(this));
});
};
}(jQuery));

getHours returns the range 0-23, so if it's greater than 11, subtract 12.
You could even get fancy and do like
(getHours() + 24) % 12 || 12

Related

Date range for cash flows

I am trying to create a cash flow with dates.
I have 2 dates: Start and End
If payments are monthly and suppose the rent payment day is on 15th. Then the cashflow would :
10/15/2018
11/15/2018
12/15/2018
1/15/2019..... and so forth until the end date.
Similarly if rent is paid every 3 months then cashflow would look like:
10/15/2018 1/15/2018 4/15/2018... and so forth.
I have the following code which works every time except when the rent is on 1st day of the month or last day of the month.
function createLedger(stDate, etDate){
if (stDate && etDate) {
var d2 = new Date(etDate);
var sDay = d2.getUTCDate();
var sMonth = d2.getUTCMonth() + 1;
var sYear = d2.getUTCFullYear();
var endOfLeaseDate = sYear + "-" + sMonth + "-" + sDay;
var d3 = new Date(stDate);
var s1Day = d3.getUTCDate();
var s1Month = d3.getUTCMonth() + 1;
var s1Year = d3.getUTCFullYear();
var startOfLeaseDate = s1Year + "-" + s1Month + "-" + s1Day;
var ddlFrequency = document.getElementById("ddFrequency");
var selectedFrequency = ddlFrequency.options[ddlFrequency.selectedIndex].value;
if (selectedFrequency) {
if (selectedFrequency == "D") {
dates = dateRange(startOfLeaseDate, endOfLeaseDate);
}
Here is where the issue is:
else if (selectedFrequency == "Q") {
dates = getQuartersDateRange(d3, d2)
dates = SortedQuarter(d3,dates);
}
else {
dates = [];
}
}
else {
dates = [];
}
createFormElement();
}
}
And i have the following codes to get the date range and quarter range.
function getQuartersDateRange(startOfLeaseDate, endOfLeaseDate) {
var dates = [];
var qlist = listQuarters(startOfLeaseDate, endOfLeaseDate);
for (var i = 0; i < qlist.length; i++) {
var yearquarter = qlist[i].split('-');
var dateQ = new Date(yearquarter[0], (yearquarter[1] * 3 - 3) + 1, startOfLeaseDate.getUTCDate());
qDay = dateQ.getUTCDate();
qMonth = dateQ.getUTCMonth();
qYear = dateQ.getUTCFullYear();
var qDate = qYear + "-" + qMonth + "-" + qDay;
dates.push(qDate);
}
return dates;
}
function SortedQuarter(startOfLeaseDate, dates) {
var qdatesSorted = [];
for (var j = 0; j < dates.length; j++) {
var month;
var splitDate = dates[j].split('-');
if (j == 0)
month = startOfLeaseDate.getUTCMonth() + 1;
else {
startOfLeaseDate.setMonth(startOfLeaseDate.getUTCMonth() + 3)
month = startOfLeaseDate.getUTCMonth() + 1;
}
var qDate = splitDate[0] + "-" + month + "-" + splitDate[2];
qdatesSorted.push(qDate);
}
return qdatesSorted;
}
function listQuarters(sDate, eDate) {
if (sDate > eDate) {
var t = eDate;
eDate = sDate;
sDate = t;
}
sDate = new Date(sDate);
sDate.setDate(2);
var startQ = getQuarter(sDate);
var endQ = getQuarter(eDate);
var result = [startQ];
while (startQ != endQ) {
sDate.setMonth(sDate.getUTCMonth() + 3);
startQ = getQuarter(sDate);
result.push(startQ);
}
return result;
}
The issue here is that when the start date = 11/1/2018 and end date = 01/31/2020
the cashflow prints as follows
11/1/2018 3/1/2019 6/1/2019 9/1/2019 12/1/2019...and so forth. So instead of going from 11/1/2018 to 2/1/2018, it skips the month and goes to the next one. I am not sure why it does that only towards the end of the month or the beginning of the month.
Any help is appreciated. Thank you.
Using moment library worked for me. aLSO, I rewrote the date range as follows:
function createLedger(stDate, etDate) {
if (stDate && etDate) {
var endOfLeaseDate = moment(etDate, "MM/DD/YYYY");
var startOfLeaseDate = moment(stDate, "MM/DD/YYYY");
dateRange(startOfLeaseDate, endOfLeaseDate);
}
}
function dateRange(stDate, etDate) {
var dates = [];
var now = etDate.clone();
var day = etDate.date();
while(now.isAfter(stDate)) {
var month = now.clone().endOf("month");
if (now.date() < day && day <= month.date()) {
now.date(day);
}
dates.push(now.format("MM/DD/YYYY"));
//dates._reverse();
now = now.clone().subtract({"months": 1});
}
console.log(dates);
}
function RunLedgerAndPV() {
var stDate = "11/26/2018";
var etDate = "09/25/2019";
createLedger(stDate, etDate);
}
RunLedgerAndPV();

Javascript not waiting for onclick

I am trying to execute this code but for some reason that I cannot figure out the RoundRobin function will execute onload rather than onclick. I have tried removing window.onload or replacing it with document.onload. All I want is for this line document.getElementById("tableButton").onclick = RoundRobin(teamsIn); to wait for the onclick trigger.
var selectedTeams = [];
window.onload = function() {
// JavaScript Document
// add selected teams to array
var teamList = document.getElementById("teamDropdown");
teamList.onchange = function addTeams() {
if (selectedTeams.length > 7) {
alert("no more teams")
} else {
var county = document.getElementById("teamDropdown").value;
selectedTeams.push(county);
}
alert("counties selected are: " + selectedTeams);
}
var teamsIn = 0;
teamsIn = selectedTeams.length;
document.getElementById("tableButton").onclick = RoundRobin(teamsIn);
// slideshow.
var imageArray = new Array();
imageArray[0] = new Image()
imageArray[0].src = "Sponsors/aib.png"
imageArray[1] = new Image()
imageArray[1].src = "Sponsors/centra.jpg"
imageArray[2] = new Image()
imageArray[2].src = "Sponsors/eircom.png"
imageArray[3] = new Image()
imageArray[3].src = "Sponsors/etihad.png"
imageArray[4] = new Image()
imageArray[4].src = "Sponsors/liberty.jpg"
imageArray[5] = new Image()
imageArray[5].src = "Sponsors/supervalu.png"
var step = 0;
function slideShow() {
document.getElementById('slideshow').src = imageArray[step].src
if (step < 5)
step++
else
step = 0
setTimeout("slideShow()", 4000)
}
function RoundRobin(teams) {
alert(teams);
var i;
var ret = "";
var round;
var numplayers = 0;
numplayers = parseInt(teams) + parseInt(teams % 2);
numplayers = parseInt(numplayers);
alert(numplayers);
var a = new Array(numplayers - 1);
var alength = a.length;
for (var x = 0; x < (numplayers); x++) {
a[x] = "Team " + (x + 1);
}
if (numplayers != parseInt(teams)) {
a[alength] = "BYE";
}
var pos;
var pos2;
ret = "----- ROUND #1-----<br />"
for (var r1a = 0; r1a < (numplayers / 2); r1a++) {
ret += a[r1a] + " vs. " + a[alength - r1a] + "<br />"
}
for (round = 2; round < alength + 1; round++) {
ret += "<br /><br />----- ROUND #" + round + "-----<br />"
ret += a[0] + " vs. " + a[alength - (round - 1)] + "<br />"
for (i = 2; i < (numplayers / 2) + 1; i++) {
pos = (i + (round - 2))
if (pos >= alength) {
pos = ((alength - pos)) * -1
} else {
pos = (i + (round - 2))
}
pos2 = (pos - (round - 2)) - round
if (pos2 > 0) {
pos2 = (alength - pos2) * -1
}
if (pos2 < (alength * -1)) {
pos2 += alength
}
ret += a[(alength + pos2)]
ret += " vs. " + a[(alength - pos)] + "<br />"
}
}
var text = document.getElementById('fixtures');
text.innerHTML = ret;
return ret
}
// round robin format
}
What's happening is that you call the function, then you assing the return value to the onclick property. For the event handler to work you need to assign a function to the property.
Wrap the call in a function expression:
document.getElementById("tableButton").onclick = function(){
RoundRobin(teamsIn);
};

Create a table to encompass part of data

I am trying to take part group of variables and add the information to a table. I have been able to add a table to encompass all the information displayed, however it does not place the information into a table that I want to see. Here is what the inital looks like (to new here to imput images): http://i.imgur.com/FxB8GMx.png - the red boxes is the information that I want divided into a table.
The information is pulled from a Sharepoint database using a soap function. I am including the place where all the variables are called:
function processResultOON(xData, status)
{
var result, subresult, outString="";
var ListTemp = new Array();
var ListUpdated = new Array();
var floatlat;
var floatlng;
var floatlatdist;
var floatlngdist;
var floatdist;
var floatdiststr;
var titletxt;
var biznametxt;
var addresstxt;
var citytxt;
var phonetxt;
var faxtxt;
var websitetxt;
var notestxt;
var cleanstr;
var ndx;
var placendx;
var swapped;
var loopcnt;
var maxndx;
var tempbizname;
var tempaddr;
var tempcity;
var temptitle;
var tempphone;
var tempfax;
var tempnotes;
var tempwebsite;
var tempdist;
var templat;
var templon;
var floattarglat;
var floattarglon;
var floatsamplat;
var floatsamplon;
var posel;
var vccsel;
var towltsel;
var towmedsel;
var towhvysel;
var lowboysel;
var dolliessel;
var motorcyclesel;
var tireltsel;
var tiremedsel;
var tirehvysel;
var winchsel;
var fuelsel;
var lockssel;
var locksmithsel;
var jumpsel;
var selOVN;
var notesstage;
var clearanceheight;
var currentinsertptr;
var currentlowdistptr;
var lowdistcheck;
var currentlowdist;
var checkptr;
var dropoutndx;
var title_ndx = 0;
var city_ndx = 1;
var businessname_ndx = 2;
var address_ndx = 3;
var phone_ndx = 4;
var fax_ndx = 5;
var notes_ndx = 6;
var lat_ndx = 7;
var lon_ndx = 8;
var website_ndx = 9;
var po_ndx = 10;
var vcc_ndx = 11;
var lowboy_ndx = 12;
var dollies_ndx = 13;
var motorcycle_ndx = 14;
var winch_ndx = 15;
var fuel_ndx = 16;
var locks_ndx = 17;
var locksmith_ndx = 18;
var jump_ndx = 19;
var OVN_ndx = 20;
var towlt_ndx = 21;
var towmed_ndx = 22;
var towhvy_ndx = 23;
var tirelt_ndx = 24;
var tiremed_ndx = 25;
var tirehvy_ndx = 26;
var clearance_ndx = 27;
var dist_ndx = 28;
var arrayndx;
var addtolist;
var addpin;
var d2 = new Date();
n2 = d2.getTime();
var count = 0;
try
{
if (status == "success" && result)
{
$(result).find("rs\\:data").each(function()
{
subresult = $(this);
$(subresult).find("z\\:row").each(function()
{
count++;
});
ListI = new Array(count);
for(var i=0;i<ListI.length;i++)
{
ListI[i] = new Array(29);
}
var d2a1 = new Date();
n2a1 = d2a1.getTime();
arrayndx = 0;
$(subresult).find("z\\:row").each(function()
{
ListI[arrayndx][title_ndx] = $(this).attr("ows_Title")
ListI[arrayndx][city_ndx] = $(this).attr("ows_City")
ListI[arrayndx][businessname_ndx] = $(this).attr("ows_Business_x0020_Name")
ListI[arrayndx][address_ndx] = $(this).attr("ows_Address")
ListI[arrayndx][phone_ndx] = $(this).attr("ows_Phone")
ListI[arrayndx][fax_ndx] = $(this).attr("ows_Fax")
ListI[arrayndx][notes_ndx] = $(this).attr("ows_Notes")
ListI[arrayndx][lat_ndx] = $(this).attr("ows_Lat")
ListI[arrayndx][lon_ndx] = $(this).attr("ows_Lon")
ListI[arrayndx][website_ndx] = $(this).attr("ows_Website")
ListI[arrayndx][po_ndx] = $(this).attr("ows_PO")
ListI[arrayndx][vcc_ndx] = $(this).attr("ows_VCC")
ListI[arrayndx][lowboy_ndx] = $(this).attr("ows_Lowboy")
ListI[arrayndx][dollies_ndx] = $(this).attr("ows_Dollies")
ListI[arrayndx][motorcycle_ndx] = $(this).attr("ows_Motorcycle")
ListI[arrayndx][winch_ndx] = $(this).attr("ows_Winch")
ListI[arrayndx][fuel_ndx] = $(this).attr("ows_Fuel")
ListI[arrayndx][locks_ndx] = $(this).attr("ows_Locks")
ListI[arrayndx][locksmith_ndx] = $(this).attr("ows_Locksmith")
ListI[arrayndx][jump_ndx] = $(this).attr("ows_Jump")
ListI[arrayndx][OVN_ndx] = $(this).attr("ows_OVN")
ListI[arrayndx][towlt_ndx] = $(this).attr("ows_Tow_x0020_light")
ListI[arrayndx][towmed_ndx] = $(this).attr("ows_Tow_x0020_medium")
ListI[arrayndx][towhvy_ndx] = $(this).attr("ows_Tow_x0020_heavy")
ListI[arrayndx][tirelt_ndx] = $(this).attr("ows_Tires_x0020_light")
ListI[arrayndx][tiremed_ndx] = $(this).attr("ows_Tires_x0020_medium")
ListI[arrayndx][tirehvy_ndx] = $(this).attr("ows_Tires_x0020_heavy")
ListI[arrayndx][clearance_ndx] = $(this).attr("ows_Clearance")
ListI[arrayndx][dist_ndx] = 0.0;
arrayndx++;
}
);
});
arrayndx = 0;
outheader="<tr>"
for (j in ListI[0])
{
outheader = outheader + "<th>" + j +"</th>";
}
outheader = outheader + "</tr>"
outString = outString + "<table>";
The information is then displayed to the show as it does in the image above using the below code. It is this information that I want to have put into a table. The question would be how do I put this information in a table without including the above unrelated information into the table?
posel = ListTemp[i][po_ndx];
vccsel = ListTemp[i][vcc_ndx];
towltsel = ListTemp[i][towlt_ndx];
towmedsel = ListTemp[i][towmed_ndx];
towhvysel = ListTemp[i][towhvy_ndx];
lowboysel = ListTemp[i][lowboy_ndx];
dolliessel = ListTemp[i][dollies_ndx];
motorcyclesel = ListTemp[i][motorcycle_ndx];
tireltsel = ListTemp[i][tirelt_ndx];
tiremedsel = ListTemp[i][tiremed_ndx];
tirehvysel = ListTemp[i][tirehvy_ndx];
winchsel = ListTemp[i][winch_ndx];
fuelsel = ListTemp[i][fuel_ndx];
lockssel = ListTemp[i][locks_ndx];
locksmithsel = ListTemp[i][locksmith_ndx];
jumpsel = ListTemp[i][jump_ndx];
selOVN = ListTemp[i][OVN_ndx];
clearanceheight = ListTemp[i][clearance_ndx];
notesstage = "";
if (posel == 1)
{
notesstage = notesstage + "<strong>PO </strong>";
}
if (vccsel == 1)
{
notesstage = notesstage + "VCC ";
}
if ((towltsel == 1) || (towmedsel == 1) || (towhvysel == 1))
{
notesstage = notesstage + "<b>Tow</b>: ";
if (towltsel == 1)
{
notesstage = notesstage + "<font color=#892EE4><b>LD </b></font>";
}
if (towmedsel == 1)
{
notesstage = notesstage + "<font color=#008080><b>MD </b></font>";
}
if (towhvysel == 1)
{
notesstage = notesstage + "<font color=#1FCB4A><b>HD </b></font>";
}
}
if (lowboysel == 1)
{
notesstage = notesstage + "Lowboy ";
}
if (dolliessel == 1)
{
notesstage = notesstage + "Dollies ";
}
if (motorcyclesel == 1)
{
notesstage = notesstage + "Motorcycle ";
}
if ((tireltsel == 1) || (tiremedsel == 1) || (tirehvysel == 1))
{
notesstage = notesstage + "<b>Tires</b> ";
if (tireltsel == 1)
{
notesstage = notesstage + "<font color=#892EE4><b>LD </b></font>";
}
if (tiremedsel == 1)
{
notesstage = notesstage + "<font color=#008080><b>MD </b></font>";
}
if (tirehvysel == 1)
{
notesstage = notesstage + "<font color=#1FCB4A><b>HD </b></font>";
}
}

Line break TextNode javascript?

I am working on a simple project which is turning out to be difficult for some reason. First let me show you the result I am getting as of now; it's just this:
Leicester City vs Manchester United - 9/21 14:30
Now, I want to have the date and time on a separate line, however, every way I tried has failed me including \n, , document.createElement("br") and some unicode characters. I've really hit a brick wall this time. Any help is welcomed.
p.s.: I am only into my 3rd month of programming
This is my code:
function listEvents(feedRoot) {
var entries = feedRoot.feed.getEntries();
var eventDiv = document.getElementById('events');
if (eventDiv.childNodes.length > 0) {
eventDiv.removeChild(eventDiv.childNodes[0]);
}
var ul = document.createElement('p');
var len = entries.length;
for (var i = 0; i < len; i++) {
var entry = entries[i];
var title = entry.getTitle().getText();
var startDateTime = null;
var startJSDate = null;
var times = entry.getTimes();
if (times.length > 0) {
startDateTime = times[0].getStartTime();
startJSDate = startDateTime.getDate();
}
var entryLinkHref = null;
if (entry.getHtmlLink() != null) {
entryLinkHref = entry.getHtmlLink().getHref();
}
var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
if (!startDateTime.isDateOnly()) {
dateString += " " + startJSDate.getHours() + ":" +
padNumber(startJSDate.getMinutes());
}
var li = document.createElement('article');
if (entryLinkHref != null) {
entryLink = document.createElement('a');
entryLink.setAttribute('href', entryLinkHref);
entryLink.appendChild(document.createTextNode(title));
li.appendChild(entryLink);
li.appendChild(document.createTextNode(' - ' + dateString));
} else {
li.appendChild(document.createTextNode(title + ' - ' + dateString));
}
ul.appendChild(li);
}
eventDiv.appendChild(ul);
}

How to close a datepicker on javascript when click somewhere outside the div?

I downloaded a simple datepicker by Marc Grabanski. I want to add him a function, the thing is I don't know javascript.
I want to close the Calendar Div when I click somewhere outside, like if I pressed the close button.
HTML:
<head>
<script src="calendar.js"></script>
<link href="calendar.css" rel="stylesheet">
</head>
<body>
<div id="calendarDiv"></div>
<h1>Modificado a partir do Original de Marc Grabanski</h1>
<br/>
<label>Data:</label>
<input type="text" class="calendarSelectDate"/>
</body>
Javascript:
/*!
* Clean Calendar
* Copyright 2007-2009 Marc Grabanski (m#marcgrabanski.com) http://marcgrabanski.com
* Project Page: http://marcgrabanski.com/article/clean-calendar
* Under the MIT License */
var popUpCal = {
selectedMonth: new Date().getMonth(),
// 0-11
selectedYear: new Date().getFullYear(),
// 4-digit year
selectedDay: new Date().getDate(),
calendarId: 'calendarDiv',
inputClass: 'calendarSelectDate',
init: function() {
var x = getElementsByClass(popUpCal.inputClass, document, 'input');
var y = document.getElementById(popUpCal.calendarId);
// set the calendar position based on the input position
for (var i = 0; i < x.length; i++) {
x[i].onfocus = function() {
popUpCal.selectedMonth = new Date().getMonth();
setPos(this, y);
// setPos(targetObj,moveObj)
y.style.display = 'block';
popUpCal.drawCalendar(this);
popUpCal.setupLinks(this);
}
}
},
drawCalendar: function(inputObj) {
var html = '';
html = '<a id="closeCalender"><img src="http://www.nzbmovieseeker.com/images/close.gif"></img></a>';
html += '<table cellpadding="0" cellspacing="0" id="linksTable"><tr>';
html += ' <td><a id="prevMonth"><b><< </b></a></td>';
html += '<td colspan="7" class="calendarHeader">' + getMonthName(popUpCal.selectedMonth) + ' ' + popUpCal.selectedYear + '</td>';
html += ' <td><a id="nextMonth"><b> >></b></a></td>';
html += '</tr></table>';
html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr>';
html += '</tr><tr class="weekDaysTitleRow">';
var weekDays = new Array('D', 'S', 'T', 'Q', 'Q', 'S', 'S');
for (var j = 0; j < weekDays.length; j++) {
html += '<td>' + weekDays[j] + '</td>';
}
var daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var numRows = 0;
var printDate = 1;
if (startDay != 7) {
numRows = Math.ceil(((startDay + 1) + (daysInMonth)) / 7);
// calculate the number of rows to generate
}
// calculate number of days before calendar starts
if (startDay != 7) {
var noPrintDays = startDay + 1;
} else {
var noPrintDays = 0;
// if sunday print right away
}
var today = new Date().getDate();
var thisMonth = new Date().getMonth();
var thisYear = new Date().getFullYear();
// create calendar rows
for (var e = 0; e < numRows; e++) {
html += '<tr class="weekDaysRow">';
// create calendar days
for (var f = 0; f < 7; f++) {
if ((printDate == today)
&& (popUpCal.selectedYear == thisYear)
&& (popUpCal.selectedMonth == thisMonth)
&& (noPrintDays == 0)) {
html += '<td id="today" class="weekDaysCell">';
} else {
html += '<td class="weekDaysCell">';
}
if (noPrintDays == 0) {
if (printDate <= daysInMonth) {
html += '<a>' + printDate + '</a>';
}
printDate++;
}
html += '</td>';
if (noPrintDays > 0) noPrintDays--;
}
html += '</tr>';
}
html += '</table>';
html += '<!--[if lte IE 6.5]><iframe src="javascript:false;" id="calendar_cover"></iframe><![endif]-->';
// add calendar to element to calendar Div
var calendarDiv = document.getElementById(popUpCal.calendarId);
calendarDiv.innerHTML = html;
// close button link
document.getElementById('closeCalender').onclick = function() {
calendarDiv.style.display = 'none';
}
// setup next and previous links
document.getElementById('prevMonth').onclick = function() {
popUpCal.selectedMonth--;
if (popUpCal.selectedMonth < 0) {
popUpCal.selectedMonth = 11;
popUpCal.selectedYear--;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
document.getElementById('nextMonth').onclick = function() {
popUpCal.selectedMonth++;
if (popUpCal.selectedMonth > 11) {
popUpCal.selectedMonth = 0;
popUpCal.selectedYear++;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
},
// end drawCalendar function
setupLinks: function(inputObj) {
// set up link events on calendar table
var y = document.getElementById('calendar');
var x = y.getElementsByTagName('a');
for (var i = 0; i < x.length; i++) {
x[i].onmouseover = function() {
this.parentNode.className = 'weekDaysCellOver';
}
x[i].onmouseout = function() {
this.parentNode.className = 'weekDaysCell';
}
x[i].onclick = function() {
document.getElementById(popUpCal.calendarId).style.display = 'none';
popUpCal.selectedDay = this.innerHTML;
inputObj.value = formatDate(popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);
}
}
}
}
// Add calendar event that has wide browser support
if (typeof window.addEventListener != "undefined")
window.addEventListener("load", popUpCal.init, false);
else if (typeof window.attachEvent != "undefined")
window.attachEvent("onload", popUpCal.init);
else {
if (window.onload != null) {
var oldOnload = window.onload;
window.onload = function(e) {
oldOnload(e);
popUpCal.init();
};
}
else
window.onload = popUpCal.init;
}
/* Functions Dealing with Dates */
function formatDate(Day, Month, Year) {
Month++;
// adjust javascript month
if (Month < 10) Month = '0' + Month;
// add a zero if less than 10
if (Day < 10) Day = '0' + Day;
// add a zero if less than 10
var dateString = Year + '-' + Month + '-' + Day;
return dateString;
}
function getMonthName(month) {
var monthNames = new Array('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
return monthNames[month];
}
function getDayName(day) {
var dayNames = new Array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
return dayNames[day];
}
function getDaysInMonth(year, month) {
return 32 - new Date(year, month, 32).getDate();
}
function getFirstDayofMonth(year, month) {
var day;
day = new Date(year, month, 0).getDay();
return day;
}
/* Common Scripts */
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null) node = document;
if (tag == null) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\s)" + searchClass + "(\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
/* Position Functions */
function setPos(targetObj, moveObj) {
var coors = findPos(targetObj);
moveObj.style.position = 'absolute';
moveObj.style.top = coors[1] + 18 + 'px';
moveObj.style.left = coors[0] + 'px';
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft, curtop];
}
Or JSFDDILE example: http://jsfiddle.net/CJEC8/
Thanks
You can create a div that lies on top of the entire page, except the date picker itself. When you click the div, you close the datepicker (and remove the div, of course).
With a simple research I think i soulve your problem.
Paste this code before the method to close when you click in the button (before: // close button link
)
// Close when loses focus.
var divEls = document.getElementsByTagName("input");
var i = 0;
for(i=0;i<divEls.length;i++)
document.getElementById(divEls[i].id).onblur = function() {
calendarDiv.style.display = 'none';
}
Man, JsFiddle is so good.
Glad to help.
This is the answer to your question
var popUpCal = {
selectedMonth: new Date().getMonth(),
// 0-11
selectedYear: new Date().getFullYear(),
// 4-digit year
selectedDay: new Date().getDate(),
calendarId: 'calendarDiv',
inputClass: 'calendarSelectDate',
init: function() {
var x = getElementsByClass(popUpCal.inputClass, document, 'input');
var y = document.getElementById(popUpCal.calendarId);
// set the calendar position based on the input position
for (var i = 0; i < x.length; i++) {
x[i].onfocus=function() {
popUpCal.selectedMonth = new Date().getMonth();
setPos(this, y);
// setPos(targetObj,moveObj)
y.style.display = 'block';
popUpCal.drawCalendar(this);
popUpCal.setupLinks(this);
}
x[i].onblur=function(){
popUpCal.hideCalendar();
}
}
},
drawCalendar: function(inputObj){
var html = '';
html = '<a id="closeCalender"><img src="http://www.nzbmovieseeker.com/images/close.gif"></img></a>';
html += '<table cellpadding="0" cellspacing="0" id="linksTable"><tr>';
html += ' <td><a id="prevMonth"><b><< </b></a></td>';
html += '<td colspan="7" class="calendarHeader">' + getMonthName(popUpCal.selectedMonth) + ' ' + popUpCal.selectedYear + '</td>';
html += ' <td><a id="nextMonth"><b> >></b></a></td>';
html += '</tr></table>';
html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr>';
html += '</tr><tr class="weekDaysTitleRow">';
var weekDays = new Array('D', 'S', 'T', 'Q', 'Q', 'S', 'S');
for (var j = 0; j < weekDays.length; j++) {
html += '<td>' + weekDays[j] + '</td>';
}
var daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var numRows = 0;
var printDate = 1;
if (startDay != 7) {
numRows = Math.ceil(((startDay + 1) + (daysInMonth)) / 7);
// calculate the number of rows to generate
}
// calculate number of days before calendar starts
if (startDay != 7) {
var noPrintDays = startDay + 1;
} else {
var noPrintDays = 0;
// if sunday print right away
}
var today = new Date().getDate();
var thisMonth = new Date().getMonth();
var thisYear = new Date().getFullYear();
// create calendar rows
for (var e = 0; e < numRows; e++) {
html += '<tr class="weekDaysRow">';
// create calendar days
for (var f = 0; f < 7; f++) {
if ((printDate == today) && (popUpCal.selectedYear == thisYear) && (popUpCal.selectedMonth == thisMonth) && (noPrintDays == 0)) {
html += '<td id="today" class="weekDaysCell">';
} else {
html += '<td class="weekDaysCell">';
}
if (noPrintDays == 0) {
if (printDate <= daysInMonth) {
html += '<a>' + printDate + '</a>';
}
printDate++;
}
html += '</td>';
if (noPrintDays > 0) noPrintDays--;
}
html += '</tr>';
}
html += '</table>';
html += '<!--[if lte IE 6.5]><iframe src="javascript:false;" id="calendar_cover"></iframe><![endif]-->';
// add calendar to element to calendar Div
var calendarDiv = document.getElementById(popUpCal.calendarId);
calendarDiv.innerHTML = html;
// close button link
document.getElementById('closeCalender').onclick = function() {
calendarDiv.style.display = 'none';
}
// setup next and previous links
document.getElementById('prevMonth').onclick = function() {
popUpCal.selectedMonth--;
if (popUpCal.selectedMonth < 0) {
popUpCal.selectedMonth = 11;
popUpCal.selectedYear--;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
document.getElementById('nextMonth').onclick = function() {
popUpCal.selectedMonth++;
if (popUpCal.selectedMonth > 11) {
popUpCal.selectedMonth = 0;
popUpCal.selectedYear++;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
},
hideCalendar:function(){
var calendarDiv=document.getElementById(popUpCal.calendarId);
calendarDiv.style.display = 'none';
},
// end drawCalendar function
setupLinks: function(inputObj) {
// set up link events on calendar table
var y = document.getElementById('calendar');
var x = y.getElementsByTagName('a');
for (var i = 0; i < x.length; i++) {
x[i].onmouseover = function() {
this.parentNode.className = 'weekDaysCellOver';
}
x[i].onmouseout = function() {
this.parentNode.className = 'weekDaysCell';
}
x[i].onclick = function() {
document.getElementById(popUpCal.calendarId).style.display = 'none';
popUpCal.selectedDay = this.innerHTML;
inputObj.value = formatDate(popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);
}
}
}
}
// Add calendar event that has wide browser support
if (typeof window.addEventListener != "undefined") window.addEventListener("load", popUpCal.init, false);
else if (typeof window.attachEvent != "undefined") window.attachEvent("onload", popUpCal.init);
else {
if (window.onload != null) {
var oldOnload = window.onload;
window.onload = function(e) {
oldOnload(e);
popUpCal.init();
};
}
else window.onload = popUpCal.init;
}
/* Functions Dealing with Dates */
function formatDate(Day, Month, Year) {
Month++;
// adjust javascript month
if (Month < 10) Month = '0' + Month;
// add a zero if less than 10
if (Day < 10) Day = '0' + Day;
// add a zero if less than 10
var dateString = Year + '-' + Month + '-' + Day;
return dateString;
}
function getMonthName(month) {
var monthNames = new Array('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
return monthNames[month];
}
function getDayName(day) {
var dayNames = new Array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
return dayNames[day];
}
function getDaysInMonth(year, month) {
return 32 - new Date(year, month, 32).getDate();
}
function getFirstDayofMonth(year, month) {
var day;
day = new Date(year, month, 0).getDay();
return day;
}
/* Common Scripts */
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null) node = document;
if (tag == null) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\s)" + searchClass + "(\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
/* Position Functions */
function setPos(targetObj, moveObj) {
var coors = findPos(targetObj);
moveObj.style.position = 'absolute';
moveObj.style.top = coors[1] + 18 + 'px';
moveObj.style.left = coors[0] + 'px';
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft, curtop];
}
I have added the
x[i].onblur=function(){
popUpCal.hideCalendar();
}
In the init function
And a new function hideCalendar after the //end drawCalendar function
// end drawCalendar function
hideCalendar:function(){
var calendarDiv=document.getElementById(popUpCal.calendarId);
calendarDiv.style.display = 'none';
},
Please keep in mind, that this is a simple fix. I would recommend using another lib for this. You can try jQuery or one of the many other datepickers out there..
--Cheers, Ex
Something like this:
html
<div id="closeCalendar"></div>
css
#closeCalendar {display:none;position:fixed; top:0; left:0; height:100%; width:100%; z-index:100;}
#calendarDiv {z-index: 200;}
js
document.getElementById('closeCalendar').onclick = function() {
document.getElementById('calendarDiv').style.display = 'none';
document.getElementById('closeCalendar').style.display = 'none';
}
...
init:
...
document.getElementById('closeCalendar').style.display = 'block';
...

Categories

Resources