Home Javascript Java Script Code of Calendar and Date Picker or Popup Calendar
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java Script Code of Calendar and Date Picker or Popup Calendar

Advertisement
This is detailed java script code that can use for Calendar or date picker or popup calendar. In the code given below there are three files...

Java Script Code of Calendar and Date Picker or Popup Calendar

     

This is detailed java script code that can use for Calendar or date picker or popup calendar. In the code given below there are three files...

1: calendar.html: Html file that shows a calendar control on the web page and a textbox that shows selected date from the date picker. 
2: calendar.js: Java script code file that contains all the java script code that has used in calendar.
3: calendra.css: CSS file that is used to give a better look to the calendar control.

This code provides some extra functionality with the calendar control like..

1: It display the current date with different color and in bold format.
2: If user already selected a date, this calendar control shows previous selected date in different color so that user can easily identify the previously selected date.
3: When user moves cursor on that date part of calendar control, color will change according to the movement of cursor.
4: When date is selected, calendar control window disappears automatically or user can close window by close 
   button in between the process.

 1. calendar.html

<head>
   <title>Java Script Calender Date Picker</title>
   <meta http-equiv="Content-Type" content="text/html;">
   <script language="javaScript" 
    type="text/javascript" src="calendar.js"></script>
   <link href="calendar.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#666666">
    <form>
      <input type="text" name="datum1"><a href="#" 
       onClick="setYears(1947, 2008);
       showCalender(this, 'datum1');">
      <img src="calender.png"></a>
    </form>
    <!-- Calender Script  --> 
    <table id="calenderTable">
       <tbody id="calenderTableHead">
         <tr>
           <td colspan="4" align="center">
	     <select onChange="showCalenderBody(
                   createCalender(document.getElementById('selectYear').value,
	           this.selectedIndex, false));"
                   id="selectMonth">
	              <option value="0">Jan</option>
	              <option value="1">Feb</option>
	              <option value="2">Mar</option>
	              <option value="3">Apr</option>
	              <option value="4">May</option>
	              <option value="5">Jun</option>
	              <option value="6">Jul</option>
	              <option value="7">Aug</option>
	              <option value="8">Sep</option>
	              <option value="9">Oct</option>
	              <option value="10">Nov</option>
	              <option value="11">Dec</option>
	          </select>
            </td>
            <td colspan="2" align="center">
	    <select onChange="showCalenderBody(createCalender(this.value, 
	      document.getElementById('selectMonth').selectedIndex, false));"
              id="selectYear">
	    </select>
			</td>
           <td align="center">
	    <a href="#" onClick="closeCalender();">
              <font color="#003333" size="+1">X</font>
            </a>
	   </td>
	</tr>
       </tbody>
       <tbody id="calenderTableDays">
         <tr style="">
           <td>Sun</td><td>Mon</td><td>Tue</td><td>Wed</td>
           <td>Thu</td><td>Fri</td><td>Sat</td>
         </tr>
       </tbody>
       <tbody id="calender"></tbody>
    </table>
<!-- End Calender Script  --> 
  </body>
</html>

2. calendar.js

 // Array of max days in month in a year and in a leap year
monthMaxDays	= [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
monthMaxDaysLeap= [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
hideSelectTags = [];
function getRealYear(dateObj)
{
	return (dateObj.getYear() % 100) + 
         (((dateObj.getYear() % 100) < 39) ? 2000 : 1900);
}
function getDaysPerMonth(month, year)
{
	/* 
	Check for leap year. These are some conditions 
        to check year is leap year or not...
	1.Years evenly divisible by four are normally 
          leap years, except for... 
	2.Years also evenly divisible by 100 are not 
          leap years, except for... 
	3.Years also evenly divisible by 400 are 
          leap years. */
	if ((year % 4) == 0)
	{
		if ((year % 100) == 0 && (year % 400) != 0)
			return monthMaxDays[month];
	
		return monthMaxDaysLeap[month];
	}
	else
		return monthMaxDays[month];
}
function createCalender(year, month, day)
{
	 // current Date
	var curDate = new Date();
	var curDay = curDate.getDate();
	var curMonth = curDate.getMonth();
	var curYear = getRealYear(curDate)
	 // if a date already exists, we calculate some values here
	if (!year)
	{
		var year = curYear;
		var month = curMonth;
	}
	var yearFound = 0;
	for (var i=0; i<document.getElementById('selectYear').options.length; 
             i++)
	{
		if (document.getElementById('selectYear').options[i].value 
                    == year)
		{
			document.getElementById('selectYear').selectedIndex = 
                        i;
			yearFound = true;
			break;
		}
	}
	if (!yearFound)
	{
		document.getElementById('selectYear').selectedIndex = 0;
		year = document.getElementById('selectYear').options[0].value;		
	}
	document.getElementById('selectMonth').selectedIndex = month;
	 // first day of the month.
	var fristDayOfMonthObj = new Date(year, month, 1);
	var firstDayOfMonth = fristDayOfMonthObj.getDay();
	continu		= true;
	firstRow	= true;
	var x	= 0;
	var d	= 0;
	var trs = []
	var ti = 0;
	while (d <= getDaysPerMonth(month, year))
	{
		if (firstRow)
		{
			trs[ti] = document.createElement("TR");
			if (firstDayOfMonth > 0)
			{
				while (x < firstDayOfMonth)
				{
				trs[ti].appendChild(document.createElement
                                ("TD"));
				x++;
				}
			}
			firstRow = false;
			var d = 1;
		}
		if (x % 7 == 0)
		{
			ti++;
			trs[ti] = document.createElement("TR");
		}
		if (day && d == day)
		{
			var setID = 'calenderChoosenDay';
			var styleClass = 'choosenDay';
			var setTitle = 'this day is currently selected';
		}
		else if (d == curDay && month == curMonth && year == curYear)
		{
			var setID = 'calenderToDay';
			var styleClass = 'toDay';
			var setTitle = 'this day today';
		}
		else
		{
			var setID = false;
			var styleClass = 'normalDay';
			var setTitle = false;
		}
		var td = document.createElement("TD");
		td.className = styleClass;
		if (setID)
		{
			td.id = setID;
		}
		if (setTitle)
		{
			td.title = setTitle;
		}
		td.onmouseover = new Function('highLiteDay(this)');
		td.onmouseout = new Function('deHighLiteDay(this)');
		if (targetEl)
			td.onclick = new Function(
                           'pickDate('+year+', '+month+', '+d+')'
                           );
		else
			td.style.cursor = 'default';
		td.appendChild(document.createTextNode(d));
		trs[ti].appendChild(td);
		x++;
		d++;
	}
	return trs;
}
function showCalender(elPos, tgtEl)
{
	targetEl = false;
	if (document.getElementById(tgtEl))
	{
		targetEl = document.getElementById(tgtEl);
	}
	else
	{
		if (document.forms[0].elements[tgtEl])
		{
			targetEl = document.forms[0].elements[tgtEl];
		}
	}
	var calTable = document.getElementById('calenderTable');
	var positions = [0,0];
	var positions = getParentOffset(elPos, positions);	
	calTable.style.left = positions[0]+'px';		
	calTable.style.top = positions[1]+'px';			
	calTable.style.display='block';
	var matchDate = new RegExp('^([0-9]{2})-([0-9]{2})-([0-9]{4})$');
	var m = matchDate.exec(targetEl.value);
	if (m == null)
	{
		trs = createCalender(false, false, false);
		showCalenderBody(trs);
	}
	else
	{
		if (m[1].substr(0, 1) == 0)
			m[1] = m[1].substr(1, 1);
		if (m[2].substr(0, 1) == 0)
			m[2] = m[2].substr(1, 1);
		m[2] = m[2] - 1;
		trs = createCalender(m[3], m[2], m[1]);
		showCalenderBody(trs);
	}
	hideSelect(document.body, 1);
}
function showCalenderBody(trs)
{
	var calTBody = document.getElementById('calender');
	while (calTBody.childNodes[0])
	{
		calTBody.removeChild(calTBody.childNodes[0]);
	}
	for (var i in trs)
	{
		calTBody.appendChild(trs[i]);
	}
}
function setYears(sy, ey)
{
	 // current Date
	var curDate = new Date();
	var curYear = getRealYear(curDate);
	if (sy)
		startYear = curYear;
	if (ey)
		endYear = curYear;
	document.getElementById('selectYear').options.length = 0;
	var j = 0;
	for (y=ey; y>=sy; y--)
	{
	document.getElementById('selectYear')[j++] = new Option(y, y);
	}
}
function hideSelect(el, superTotal)
{
	if (superTotal >= 100)
	{
		return;
	}
	var totalChilds = el.childNodes.length;
	for (var c=0; c<totalChilds; c++)
	{
		var thisTag = el.childNodes[c];
		if (thisTag.tagName == 'SELECT')
		{
		if (thisTag.id != 'selectMonth' && thisTag.id != 'selectYear')
		{
		var calenderEl = document.getElementById('calenderTable');
		var positions = [0,0];
		var positions = getParentOffset(thisTag, positions);	// nieuw
		var thisLeft	= positions[0];
		var thisRight	= positions[0] + thisTag.offsetWidth;
		var thisTop	= positions[1];
		var thisBottom	= positions[1] + thisTag.offsetHeight;
		var calLeft	= calenderEl.offsetLeft;
		var calRight	= calenderEl.offsetLeft + calenderEl.offsetWidth;
		var calTop	= calenderEl.offsetTop;
		var calBottom	= calenderEl.offsetTop + calenderEl.offsetHeight;
		if (
		(
		// check if it overlaps horizontally 
		(thisLeft >= calLeft && thisLeft <= calRight)
		||
		(thisRight <= calRight && thisRight >= calLeft)
		||
		(thisLeft <= calLeft && thisRight >= calRight)
		)
		&&
		(
		// check if it overlaps vertically 
		(thisTop >= calTop && thisTop <= calBottom)
		||
		(thisBottom <= calBottom && thisBottom >= calTop)
		||
		(thisTop <= calTop && thisBottom >= calBottom)
		)
		)
		{
		hideSelectTags[hideSelectTags.length] = thisTag;
		thisTag.style.display = 'none';
		}
		}
		}
		else if(thisTag.childNodes.length > 0)
		{
			hideSelect(thisTag, (superTotal+1));
		}
	}
}
function closeCalender()
{
	for (var i=0; i<hideSelectTags.length; i++)
	{
		hideSelectTags[i].style.display = 'block';
	}
	hideSelectTags.length = 0;
	document.getElementById('calenderTable').style.display='none';
}
function highLiteDay(el)
{
	el.className = 'hlDay';
}
function deHighLiteDay(el)
{
	if (el.id == 'calenderToDay')
		el.className = 'toDay';
	else if (el.id == 'calenderChoosenDay')
		el.className = 'choosenDay';
	else
		el.className = 'normalDay';
}
function pickDate(year, month, day)
{
	month++;
	day	= day < 10 ? '0'+day : day;
	month	= month < 10 ? '0'+month : month;
	if (!targetEl)
	{
		alert('target for date is not set yet');
	}
	else
	{
		targetEl.value= day+'-'+month+'-'+year;
		closeCalender();
	}
}
function getParentOffset(el, positions)
{
	positions[0] += el.offsetLeft;
	positions[1] += el.offsetTop;
	if (el.offsetParent)
	  positions = getParentOffset(el.offsetParent, positions);
	return positions;
}

Save both files in same directory along with the file calendar.css and an image 'calender.png'. To run calendar control, run calendar.html file and select the appropriate month, year and date.

When user clicks on the button adjacent to text box, a calendar will appear on the web page....

In the appeared calendar we can select month, year and date. After date selection calendar window will disappear automatically and selected date is shown in text box.

 

Download Source Code

     

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 29, 2008

Related Tutorials

Ask Questions?    Discuss: Java Script Code of Calendar and Date Picker or Popup Calendar   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
arvind kumar
April 12, 2011
pop up calender

sir, your are exellent.i hope in future you will be more helpful to us.thanks
Nutan Sharma
April 18, 2011
java script

when I put this code in my project it gives error, that Object expexted at html file setYear(this,'dob')
james
May 27, 2011
change

i want to change the format of it to month/day/year
dhanabal
May 29, 2011
could not assign that date to text box

the main one is cursor can move the over day numers,could not show hand symbol that mean on click event did not assigned to it,reply me sir
zorigoo
June 29, 2011
Thanks

More more
Andreas
August 26, 2011
Calendar and Date Picker

Thanks for your script. I try to use it twice in the same form but it isn't working. Can you tell me what should I change? Thanks. John
Sanjay kumar
August 26, 2011
nice

i have used dis code dis is working very fine....i love dis site...
sandy
June 6, 2013
confused!

how to append these HTML code and JS code in above
sanju
June 6, 2013
confused!

how to append these HTML codes and JS codes
credit loans
September 24, 2011
respond

The business loans seem to be essential for people, which want to start their own organization. In fact, it is very easy to get a auto loan.
pravin
January 17, 2012
Hi

good calender
Yoon Moe
January 11, 2013
Question

how can do for 2013 to 2100 according to ascending?
Duc Tung
February 20, 2012
How to make 2 calendar on a website?

If I want to make 2 calendar on a website to take to 2 difirent date string, I will need how to make?
RAMYA
February 21, 2012
Convert dd/mm/yy into yy/mm/dd

The calendar coding is quite easy to understand... Thanks for the easy coding. Can anyone send me the coding to convert the date format from dd/mm/yy into yy/mm/dd
GGGames
March 12, 2012
Duda

Esta interesante el artículo pero tengo una duda: Y si deseo agregar varios inputs cada uno con su calendario en la misma página? Ya intenté cambiando los id pero no corre ... Muchas gracias por tu respuesta
Mike
March 13, 2012
2 Calendar on the same page

Hi, Thanks for tour awesome tutorial. I am designing a website for my final project. It is for a flight service and I am trying to implement 2 calendars on the page (one for arrival date and the other departure date). I have tried to implement your code and have instantiated it, however, only one works. Can you help me out, please?
ambusher
March 20, 2012
code

awesome job
Hana
March 26, 2012
question regarding this code

what if I need to change the years, start from current year 2012 till 2020, what should I change on that code
Bhushan
April 12, 2012
Regarding Error while combining this code with jsp

thanx sir, for this code. but while attaching this code with jsp. the combine code is not able to run perfectly. it display the calender and close it very well. but unable to print date on selection of particular date. my jsp code is:- <%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %> <%@ taglib prefix="tab" uri="http://ditchnet.org/jsp-tabs-taglib" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <html> <head> <meta http-equiv="Content-Type" content="text/html;"> <title>Server Admin Panel</title> <link href="tpcss.css" rel="stylesheet" type="text/css" /> <script src="SpryAssets/SpryCollapsiblePanel.js" type="text/javascript"></script> <script language="javaScript" type="text/javascript" src="calendar.js"></script> <link href="calendar.css" rel="stylesheet" type="text/css"> <script language="javascript"> function addDate(){ date = new Date(); var month = date.getMonth()+1; var day = date.getDate(); var year = date.getFullYear(); var hr=date.getHours(); var mini=date.getMinutes(); var sec=date.getSeconds(); 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"; var n = weekday[date.getDay()]; if (document.getElementById('date').value == ''){ document.getElementById('date').value =n+'-'+day + '/' + month + '/' + year; } } </script> <link href="SpryAssets/SpryCollapsiblePanel.css" rel="stylesheet" type="text/css" /> </head> <body onLoad="addDate();"> <form> <font class="middle-font" > Welcome to Wi-Fi Security</font> <div align="right">Today is:-<input type="text" id="date" class="alignclock" maxlength="80" style="width:300px"></div> </form> <form> <input type="text" name="datum1"><a href="#" onClick="setYears(2000, 2020); showCalender(this, 'datum1');"> <img src="calender.png"></a> </form> <!-- Calender Script --> <table id="calenderTable"> <tbody id="calenderTableHead"> <tr> <td colspan="4" align="center"> <select onChange="showCalenderBody(createCalender(document.getElementById('selectYear').value, this.selectedIndex, false));" id="selectMonth"> <option value="0">Jan</option> <option value="1">Feb</option> <option value="2">Mar</option> <option value="3">Apr</option> <option value="4">May</option> <option value="5">Jun</option> <option value="6">Jul</option> <option value="7">Aug</option> <option value="8">Sep</option> <option value="9">Oct</option> <option value="10">Nov</option> <option value="11">Dec</option> </select> </td> <td colspan="2" align="center"> <select onChange="showCalenderBody(createCalender(this.value, document.getElementById('selectMonth').selectedIndex, false));" id="selectYear"> </select> </td> <td align="center"> <a href="#" onClick="closeCalender();"><font color="#003333" size="+1">X</font></a> </td> </tr> </tbody> <tbody id="calenderTableDays"> <tr style=""> <td>Sun</td><td>Mon</td><td>Tue</td><td>Wed</td><td>Thu</td><td>Fri</td><td>Sat</td> </tr> </tbody> <tbody id="calender"></tbody> </table> <!-- End Calender Script --> <div id="CollapsiblePanel1" class="CollapsiblePanel"> <div class="CollapsiblePanelTab" tabindex="0">Login History</div> <div class="CollapsiblePanelContent"><font face="Times New Roman, Times, serif" size="4"><center><br />Please insert Date and Time for checking Login History of Specified Duration</center></font> <br /> <font class="textbx" style="position:fixed;left:310px;top:143px">Date &nbsp;<input type="text" id="datetxt" placeholder="Please Enter Date" size="20" style="position:fixed;left:350px;top:140px" /></font> <font class="textbx" style="position:fixed;left:550px;top:143px">Time &nbsp;<input type="text" id="hr1txt" size="20" style="position:fixed;left:600px;top:140px;width:30px;" />&nbsp;&nbsp;&nbsp;<input type="text" id="mn1txt" size="20" style="position:fixed;left:640px;top:140px;width:30px;"/><font class="textbx" style="position:fixed;left:680px;top:143px"> To &nbsp;<input type="text" id="hr2txt" size="20" style="position:fixed;left:710px;top:140px;width:30px;" />&nbsp;&nbsp;&nbsp;<input type="text" id="mn2txt" size="20" style="position:fixed;left:750px;top:140px;width:30px;" /></font></font> <input type="submit" id="logsearch" name="Search" value="Search" style="position:fixed;left:800px;top:135px;width:100px;height:30px" /> Content</div> </div> <div id="CollapsiblePanel2" class="CollapsiblePanel"> <div class="CollapsiblePanelTab" tabindex="0">Find Students</div> <div class="CollapsiblePanelContent"> Content</div> </div> <div id="CollapsiblePanel3" class="CollapsiblePanel"> <div class="CollapsiblePanelTab" tabindex="0">Current Login</div> <div class="CollapsiblePanelContent">Content</div> </div> <script type="text/javascript"> var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel1"); var CollapsiblePanel2 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel2", {contentIsOpen:false}); var CollapsiblePanel3 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel3", {contentIsOpen:false}); </script> </body> </html> pls help to remove this problem
iqbal mulani
May 31, 2012
calendar

it's working very well.
balavishnu
June 4, 2012
Extending the year

I want to extend the year till 2013. pls help me
balavishnu
June 4, 2012
Thankyou very much

Its gr8.. I was looking for this for a long time :) Thx for ur help...
vimlesh
June 10, 2012
Java Script Code of Calendar

this code is very good and easy to implement and understandable......nice.
rishita
July 6, 2012
calendar

thanks a lot.
spandana
August 16, 2012
failed to work in mozilla

I induced the above code in jsp page, the calendar worked well in IE and browser in eclipse, but in mozilla the calendar is displayed but i'm unable to select the date.
manisha garg
August 22, 2012
regarding month case in output of calendar...

hey dis is vry awsum code nd wrkng fyn but i have a doubt-jow cn i get month as jan,feb.. written in output..i have changed d values in html code but still not getting the required output as- 12-AUG-2012
jaimin
August 25, 2012
java script

post more java script
Akshita
September 18, 2012
If the upper limit is increased to 2020

This is not working.
manish
November 3, 2012
request for calender picker

hi,i need php code for calender picker with textbox/dropdown list..can any one help me..? thanks in advance..
YOGESH MEHER
April 3, 2013
THANKS

REALLY UR CODE IS VERY NICE,HELPFUL TO ME...THANK YOU,,,,
fitri ahmad
April 25, 2013
pertanyaan

this is good website..it can help me to to my final project..
sivaji
July 5, 2013
Question Regarding Validation

Hi Sir I would like do one validation according to my requirement.Which is I want to disable all previous dates how can we do this please help me on this thank in advance..
xxx
February 13, 2014
request

delete this code.. add some new one.. so that everybody can used//
shiva
May 19, 2014
i want java screept to hide my tex booxes

what a great code
Francis Appiah
February 16, 2012
How to add another year

Am here by asking how can add another year into the already year.
simo rahouti
August 1, 2012
updating the calendar

I want to update the year select, can you help me to do it please!
DMCA.com