+40 745 232 788

Online Solutions Development Blog   |  

RSS

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[
    mce:0
// ]]></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js">// <![CDATA[
    mce:1
// ]]></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>
<pre></pre>
<div id="datepicker"></div>
<pre>

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:
    $(document).ready(function()
    {
    	var selected_dates = new Array();
    	// gets all the events from the database using AJAX
    	selected_dates = getSelectedDates();
    
    	$('#datepicker').datepicker({
    		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
    			$("#dialog").dialog("option","title",selected_dates[date]['event_title']);
    			// puts the event's description text in the dialog box
    			$("#dialog").text(selected_dates[date]['event_description']);
    			// 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();
        $.ajax(
        {
            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:

CREATE TABLE IF NOT EXISTS `events` (
  `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();
try
{
	$stmt = $dbh->query('
							SELECT
								*
							FROM
								events
			   			');
}
catch (PDOException $e)
{
	print($e->getMessage());
	die;
}
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. Hi
    Nice calendar 😉
    I have one little question… How can I change names of week’s day and months names to other language?

    I will be grateful 😉

    • Hello, Salan. You can take a look on a example on how to change the language of the calendar from here: http://jqueryui.com/datepicker/#localization

      All you have to do is to add the language javascript file (For example for French you have to add this:

      <script src="//jqueryui.com/resources/demos/datepicker/jquery.ui.datepicker-fr.js"></script>

      )
      After that, before you initialize the datepicker, you have to add this row:

      $( "#datepicker" ).datepicker( $.datepicker.regional[ "fr" ] );

      Hope this helps!

  2. Hi again 😉
    Do you give me more tips?
    I would like to change to Polish language. How can I exactly do this?

    • Hello,
      This is something that has nothing to do with the purpose of this blog post, it is about how the jQuery UI datapicker can be customized. Andreea already gave you a link which you already had from the post, it’s basically another section from the official documentation (the very first link in this post). From this point on you should research how to customize this plugin to fit your needs. You can take Andreea’s example and download the javascript file for French, rename it, translate it, save it in your project and use it.

  3. Thank you, now I know what I should to do.

  4. Hi, Great calendar.. but I have little problem with it.
    calendar works great on one server, but if I upload this same calendar with this same code, calendar doesn’t show events. I’ve changed host, user, password, and db and of course I’ve created datebase on this server. I don’t have connect error, but only calendar doesn’t show events…
    any ideas?

  5. of course if I upload to other server

  6. script didn’t work because I had to change in htacess file PHP 5.

    It is possible to add cyclic event. For example I would like to add event which is in every Friday.

  7. How can I make a dynamic calendaring, where I can define each day of the year at the the beginning of the year as Human Resource Manager of the company.
    for example : I want to define
    January 1, 2013 : is a holiday and the color of the date becomes red.
    another example : March 10 , 2013 is a national holiday and the color of the date becomes red.
    Please advise me how to develop it or if there are any script references available.
    Thank you so much for the help.

    • Hello, Gani.

      From what I understand you have two questions:
      1) how can a certain selected date be styled?
      2) how can events be added to this list?

      Both things are covered in the tutorial:

      You can see that the script adds a class called “my_class” to the selected dates. You can change that name to anything you want and you can use CSS to create a class that makes the dates look the way you want them to (like red or any other color).

      To add events you just need to save them in that events table if you decide to use the exact same database structure. In the example you have a table called events with a column called event_date. You just need to save data to that table. It is up to you how you will do that: you can create a script to manage events in that table, you can just use something like phpMyAdmin to add records to it or any other way you might think of.

  8. Thanks a lot Andreea,
    you saved my day!

    To be perfect I only need to NOT have any link or pop-up showing when I click on the day box, I just need to have the busy days colored in a different way but not clickable.
    Is this a difficult task?

    Thanks again

    • Hello Roberto!
      It’s not difficult. The dialog is called in the onSelect section from the javascript code with the code

      $("#dialog" ).dialog();

      If you don’t put anything in that section, there won’t be any dialog showing.
      Also, don’t forget to delete the line that sets the HTML of the dialog, because you will have the text from the dialog box in a div on the page instead of in a popup:

      $("#dialog").html("...");
  9. Hello. I have strange problem with this datapicker. However i love this solution with dates.
    Ok, When I click on the data I have new window with title for example test2 and when I click on the next data I have this same title, even in databas title is another. Why dose it happen?

    Best wishes Marek.

  10. sorry for my mistakes
    …database
    ….does

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