+40 745 232 788

Online Solutions Development Blog   |  


Dynamic Jquery Datepicker calendar

posted by ,
Categories: JavaScript
Taggs , , , , , ,

Have you ever wanted to know what do you have to do tomorrow or in the next week without checking your agenda?

Today I’m going to show you how to use JQuery Datepicker and AJAX  to create a calendar that looks like this:

jquery calendar

This dynamic datepicker calendar will allow users to click on a date and see the events. It’s easy to create and very useful. The best part is that only the dates from the calendar that contain events are the clickable ones. Only by watching you will quickly see in what days of the month you have events. Now let’s begin!

To create a jquery calendar we will use a HTML file, a Javascript file and a PHP file requested with AJAX. Let’s begin!

1. The html file

This is the file you’re going to see in the browser. This file is the most important one because it contains the link to the JQuery libraries and the stylesheets.

<!-- stylesheets -->

<!-- js files -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">// <![CDATA[
// ]]></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js">// <![CDATA[
// ]]></script>

Now that we’ve included the libraries, we have to add the output somewhere in the page. For this we’ll use 2 div elements (remember their ids because you’ll need them in the code). You don’t need to populate them. Just leave them like that.

<!-- this div is used for the dialog box --></pre>
<div id="dialog"></div>
<div id="datepicker"></div>

2. The javascript file

You can also put this code in the html file between the “<script>” tags. This script will have 2 parts:

  • The first part contains the function that is invoked when the page is loaded:
    	var selected_dates = new Array();
    	// gets all the events from the database using AJAX
    	selected_dates = getSelectedDates();
    		dateFormat: 'yy-m-d',
    		inline: true,
    		beforeShowDay: function (date)
    			// gets the current month, day and year
    			// Attention: the month counting starts from 0 that's why you'll need to +1 to get the month right
    			var mm = date.getMonth() + 1,
    				dd = date.getDate(),
    				yy = date.getFullYear();
    			var dt = yy + "-" + mm + "-" + dd;
    			if(typeof selected_dates[dt] != 'undefined')
    				// puts a special class to the dates in which you have events, so that you could distinguish it from the other ones
    				// the "true" parameter is used to know which are the clickable dates
    				return [true, " my_class"];
    			return [false, ""];
    		onSelect: function(date)
    			// puts the event's title in the dialog box
    			$("#dialog").attr("title",selected_dates[date]['event_title']); // for the first time you open the popup
    			// puts the event's description text in the dialog box
    			// show the dialog box
    			$("#dialog" ).dialog();
  • The second part is the function that returns all the events from the database using AJAX:
    function getSelectedDates()
    	var the_selected_dates = new Array();
            url: 'events.php',
            dataType: 'json',
            async: false,
            success: function(data)
    			$.each(data, function(n, val)
                    the_selected_dates[val.event_date] = val;
        return the_selected_dates;

This is just an example of what you can obtain in the dialog box. You can also add a date (or anything else). There’s no limit.

3. As you can see in the javascript file, we have a PHP document requested with AJAX. You’ll need a database that has the events which you want to show. This is the code for creating the table that we will use:

  `event_id` int(11) NOT NULL auto_increment,
  `event_date` date NOT NULL,
  `event_title` varchar(100) NOT NULL,
  `event_description` text NOT NULL,
  PRIMARY KEY  (`event_id`)

In events.php, take all the events and put them in array. Now encode it in a json.
NOTE: I recommend you to customize this function and take only the events from the month/year where you have a large database.

$dates = array();
	$stmt = $dbh->query('
catch (PDOException $e)
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
	// because $row['event_date'] will have this form: 2012-01-10 and in Javascript we have 2012-1-10, we need to rewrite it in the way we use it in Javascript, so we could compare it
	$row['event_date'] =  date("Y-n-j", strtotime($row['event_date']));
	$dates[] = $row;
echo json_encode($dates);

You can download an archive with the code here.

If you have questions or suggestions please, don’t hesitate to tell me.

If you liked this post
you can buy me a beer

76 Responses to Dynamic Jquery Datepicker calendar

  1. Is there an easy way for the popup text to use html markup?

    • Yes, it’s quite very easy. Instead of (“#dialog”).text you put (“#dialog”).html. Example:

      // put the event's description text in the dialog box 
      $("#dialog").html('<span style="color: red">' + selected_dates[date]['event_description'] + '</span>');
  2. Is there a way to go to another page and use the event_id in a URL query string?
    So a click event would take you to a details page such as events.php?id=123
    The reason for the event_id over a date is so you can handle date ranges such as where an event lasts multiple days.

  3. Of course there is a way. You have to modify two things. In the HTML file you have to create a very simple form like this:

    <form action="events_details.php" id="events_details" method="get">
    <input type="hidden" name="id" />

    Now you have to populate the “id” input and to submit the form. In the JS file, instead of opening a dialog, you do this:

    onSelect: function(date)

    Now you’re going to a page like this: events_details.php?id=2

    I hope this is what you needed.

  4. Wow you make it look so easy… Thanks.

    May I ask another question… what if you have a date range. How do you make the calendar show a range from a start date to an end date and still retain the recordID as you have demonstrated above?

    For instance, here is the JSON values that have a starting and end date:

    [{“event_day”:”2012-2-10″,”event_id”:”2″,”event_title”:”test”,”event_desc”:”test description”,”event_day_to”:”2012-02-10″},{“event_day”:”2012-2-15″,”event_id”:”4″,”event_title”:”test title “,”event_desc”:”Some stuff here as a description”,”event_day_to”:”2012-02-18″}]

    This seems considerably more difficult as you would need to figure cross month dates. Thanks again!

    • I’m not sure what you do you want to do, so I have to ask you first…do you want to have events that last several days (like event4 from 2012-2-15 to 2012-02-18)? And when you click on to one of the days from that event (let’s say you click on 2012-02-16) you want it to go to events_details.php?id=4 ?
      Waiting for your reply to see exacly what I should explain.

  5. Hello,
    Yes, if you see the JSON there are two events… One that is a single day event:
    {“event_day”:”2012-2-10″,”event_id”:”2″,”event_title”:”test”,”event_desc”:”test description”,”event_day_to”:”2012-02-10″}

    and the other, an event that spans multiple days:
    {“event_day”:”2012-2-15″,”event_id”:”4″,”event_title”:”test title “,”event_desc”:”Some stuff here as a description”,”event_day_to”:”2012-02-18″}

    Then as you say, either one links to their respective event_id which allows me to construct a event detail page populated if any of the dates are selected when there is a multi-day event since they all share the same event_id.

    • Ok… the trick is in the PHP file where you take the dates from the database. There, instead of just putting the dates in a array and send them to JS file, you have to go through all the days from “event_day” to “event_day_to”. You’ll have to do something like this:

      while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
      	for($start_date = strtotime($row['event_day']); 
      	$start_date <= strtotime($row['event_day_to']); 
      	$start_date = $start_date + 24*3600)
      		$row['event_date'] 	=  date("Y-n-j", $start_date);
      		$dates[] = $row;

      And this way it doesn’t matter if a event goes from a month to another. I hope this is what you need to do.

      • Thank you Andrea. May God bless you greatly. Dynamic Jquery Datepicker calendar, which was the need for the system reseras I’m developing.

  6. Good Afternoon, I would like to know how to show two events registered on the same date.

  7. Hello.
    FIRST: You have to modify the PHP file and to organize the events depeding on the date they start. Example:

    //$dates[] = $row;
    $dates[$row['event_date']][] = $row;

    SECOND: In your script you have to change the getSelectedDates() function like this:

    // the_selected_dates[val.event_date] = val;
    the_selected_dates[n] = val;

    THIRD: Modify the main js function. For example, I made this to just concatenate the title and the description within the popup (you have to modify only the onSelect: function(date) part):

    onSelect: function(date)
    	var dialog_title = " ";
    	var dialog_html = " ";
    	$.each(selected_dates[date], function(n, val)
    		dialog_title = dialog_title + " " + val.event_title;
    		dialog_html = dialog_html + "<hr />" + val.event_description;
    	// put the event's title in the dialog box 
    	$('#dialog').attr("title", dialog_title);
    	// put the event's description text in the dialog box 
    	// show the dialog box
    	$("#dialog" ).dialog();

    I hope this helps you. Have a nice day!

  8. Good morning, I’m still a problem and doubts.
    I’m doing a calendar for booking a comDominio environment,
    problem: When the bank records date with two different title, to open a evendo in the calendar it shows me all right, when closing and opening another event that he shows me the title of an earlier date.
    Doubt: it would be a doubt, if I want to leave the dates enabled for the User to choose a date to book, is? and has more than one place as a title data because the environment would be the title, a date and may be over a different environment. I thank you note.

    • Hi, Rafael… I really can’t tell what you’re doing wrong without seeing the code. If you want the users to be able to click on all the dates, just put this instead of the beforeShowDay function:

              beforeShowDay: function (date)
                      return [true, " my_class"];
  9. Very good code, only that I returning an error, say the bank added two events: an event on 27/04 and another on 28/04, with different titles, when I open the dialog the first 27 days and then 28 days does not change the title, only changes when I update the page and open the other day.

  10. Andreea is to create a table inside the dialog, where in my print column in another column event and the event time?

    • Hello, Marcelo. As I said in a previous comment, instead of “(“#dialog”).text(‘your text’)” you can put



      I hope this helps you.

Add a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Also, if you want to display source code you can enclose it between [html] and [/html], [js] and [/js], [php] and [/php] etc