Home / Articles / Programming languages / Scripting languages / JavaScript / jQuery UI. Widgets. Datepicker (Calendar)

jQuery UI. Widgets. Datepicker (Calendar)

jQuery UI. Widgets. Datepicker (Calendar)
 
  • Currently 4.5 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 4.5/5 (5 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.


Just wanted to explain that this article is not intended for hardcore pros, it is just a push to self-development, a kind of a small tour which explains the possibilities for beginners, for those who have no idea about UI (User Interface) in specific and jQuery as a whole. Well, let's go!

Download here.
Connecting the magical framework, location for the calendar and style sheet:

<link type="text/css" href="css/ui-lightness/jquery-ui-1.9.1.custom.min.css" rel="stylesheet" />
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.9.1.custom.min.js" type="text/javascript"></script>
<script src="js/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script>

So, the preparations are complete.

To create a calendar all you need is only one HTML line:

<input id="datepicker" type="text" />

Or if you want to embed a calendar to your site as part of the page:

<div id="datepicker"></div>

And a couple of lines of js:

$(function(){
  $.datepicker.setDefaults(
    $.extend( $.datepicker.regional[ '' ] )
  );
  $( '#datepicker' ).datepicker();
});

Live demo

And so now we have a working calendar in English, but what if we want to make the site in German or French? To change everything according to our needs you have to change only one setting, and this can be done dynamically:

$( '#datepicker' ).datepicker( 'option', $.datepicker.regional[ 'de' ] );

Live demo

The standard "default" is not always enough to execute various tasks. So let's just a little bit edit the settings:

$( '#datepicker' ).datepicker({
  minDate: '-30', //The minimal date that can be selected, i.e. 30 days from the "now"
  maxDate: '+1m +1w +3d' //The maximal date that can be selected, i.e. + 1 month, 1 week, and 3 days from "now"
});

Live demo

Events

$.datepicker.setDefaults($.extend(
  $.datepicker.regional[ '' ])
);
$( '#datepicker' ).datepicker({
  beforeShow: function(input) {
    $( input ).css( 'background-color', '#ff9' );
  },
  onSelect: function(dateText, inst) {
    $( this ).css( 'background-color', '' );
    alert( 'Selected: ' + dateText +
      "\n\nid: " + inst.id +
      "\nselectedDay: " + inst.selectedDay +
      "\nselectedMonth: " + inst.selectedMonth +
      "\nselectedYear: " + inst.selectedYear);
  },
  onClose: function(dateText, inst) {
    $( this ).css( 'background-color', '' );
  }
});

Live demo

Listed above we've got three options, which contain callbacks. beforeShow - this function is triggered before the calendar is displayed. With the help of css-option the INPUT will be set to yellow background. In onSelect a certain function is defined, which will be triggered when you select date, it will display the selected date in alert and assign value to css-option as empty, that will return INPUT to the prior state. onClose function is triggered when closing the calendar - that is, it will return INPUT as White background.

Methods

<a id="datepicker_open">Open in a window</a>
$.datepicker.setDefaults( $.extend( { changeYear: true }, $.datepicker.regional[ 'ru' ] ) );
  $( '#datepicker_open' ).click(function(){
    $( '#datepicker' ).datepicker(
      'dialog',
      '23.04.2009',
    function(){
      alert( 'Event onSelect' );
    },
    { showButtonPanel: true }
  );
});

Live demo

In this example, I will demonstrate the work of the dialog method. We call this method by clicking on the link. The first argument is the name of the method, the second argument textDate - the default date on which calendar opens. In the argument onSelect we can set callback-function which will be called when selecting a specific date in the calendar. In the argument settings you can define an object with the new widget settings that will be applied to the calendar, which will open in the dialog window.

Well, I guess that's about it... Use it! And the following is a list of all the options, methods, and events.

Options:

  • altField - jQuery selector for another field which should be updated when a date is selected from the Datepicker. The date format in this additional field is set with the option altFormat.
  • altFormat - the date format which will be used for altField option. These settings allow the user to see one date format, whereas for the calculations a different format can be used. A complete list of formats can be found here http://docs.jquery.com/UI/Datepicker/formatDate
  • appendText - text which is displayed after each date input field. Can be used, for example, to mark the field as required.
  • buttonImage - address of the button's popup image, which can be used to call the calendar. Used in conjunction with showOn, when it has the values "button" or "both". If the text has been set in the option buttonText, it becomes the value of the attribute alt of the image and is not displayed.
  • buttonImageOnly - if this option is true, the image, whose address is defined in the option buttonImage, will appear not on the button, but by itself and will work as a trigger.
  • buttonText - the text that will be displayed on the button, which you can use to call the calendar. Used in conjunction with showOn, when it has the values "button" or "both".
  • changeMonth - if this option is enabled by setting the value as true, it will allow to select the month from the drop-down list.
  • changeYear - if this option is enabled by setting the value as true, it will allow to select the year from the drop-down list.
  • closeText - this option is used in conjunction with showButtonPanel, if the latter is set to true. The value of the option closeText is defined in the localization file, if it is in use, but this value can be redefined by specifying it.
  • constrainInput - by default this option is set to true, and constrains the date format, defined in the options of the widget, in the input field. If you don't want to follow this format, set the option to false.
  • currentText - is used in conjunction with showButtonPanel, if the latter is set to true. The value of currentText option is defined in the localization file, if it is in use, but this value can be redefined by specifying it.
  • dateFormat - defines the format of the date. The value of dateFormat option is defined in the localization file, if it is in use, but this value can be redefined by specifying it. A complete list of all the formats can be found here http://docs.jquery.com/UI/Datepicker/formatDate
  • dayNames - an array containing the long names of the days of the week, starting from Sunday. Defined in the localization file, if it is in use, but this value can be redefined by specifying it.
  • dayNamesMin - an array of minimized 2-character names for days of the week, starting from Sunday. Defined in the localization file, if it is in use, but this value can be redefined by specifying it.
  • dayNamesShort - an array of minimized 3-character names for days of the week, starting from Sunday. Defined in the localization file, if it is in use, but this value can be redefined by specifying it.
  • defaultDate - sets the date, which will be highlighted on the first opening if the date field is empty. The option can be specified through the object Date, or as a number of days from the current day (e.g. +7 or -15), or as a string of values, which determine period ("y" for years, "m" for months, "w" for weeks, "d" for days, e.g. "+1 m +7 d"), and finally as null for current day.
  • duration - the duration of the animation effect when opening (closing) the calendar. Can have values of speeds in a string - "fast", "normal" (default), "slow" or time-number in milliseconds. If you leave the string empty, the calendar will be opened and closed without animation effects.
  • firstDay - sets the first day of the week: Sunday - 0, Monday - 1,... Defined in the localization file, if it is in use, but this value can be redefined by specifying it.
  • gotoCurrent - if this option is set to true, the button "Today" (only with showButtonPanel set to true) will point at the selected date instead of the current one.
  • hideIfNoPrevNext - if you constrain the range of available dates with options minDate and maxDate, then when you reach the end of the range, arrows "Back" and "Forward" will be disabled. But they can be completely hidden, by setting option hideIfNoPrevNext to true.
  • isRTL - this option must be set to true, if you are using a language written from right-to-left. Defined in the localization file, if it is in use.
  • maxDate - sets the maximum possible selectable date through the object Date, or as a number of days from the current day (e.g. +7), or as a string of values, which determine period ("y" for years, "m" for months, "w" for weeks, "d" for days, e.g. "+1 y +1 d"), or null for no limit.
  • minDate - sets minimum selectable date via Date object, or as a number of days from the current day (eg -7), or as a string of values, which determine period ("y" for years, "m" for months, "w" for weeks, "d" for days, e.g. "-1y-1m"), or null for no limit.
  • monthNames - an array containing the long month names. Defined in the localization file, if it is in use, but this value can be redefined by specifying it.
  • monthNamesShort - an array of abbreviated months names to 3-character. Defined in the localization file, if it is in use, but this value can be redefined by specifying it.
  • navigationAsDateFormat - by default the option is set to false. If set true, the function dateFormat will be applied to the values of the options nextText, prevText and currentText in order to display the previous and next month names when navigating.
  • nextText - the text displayed as a link for the next month. Defined in the localization file, if it is in use, but this value can be redefined by specifying it. If you use a stylesheet file ThemeRoller, this value is replaced by an icon.
  • numberOfMonths - This option sets the number of months to show at the same time. The value of the option may be either a number (straight integer) or an array consisting of two elements, which define, respectively, the number of rows and columns. For example, with two-elements [2, 3] the calendar will be displayed in two rows each having three months.
  • prevText - the text displayed as a link to the previous month. Defined in the localization file, if it is in use, but this value can be redefined by specifying it. If you use a stylesheet file ThemeRoller, this value is replaced by an icon.
  • shortYearCutoff - by default +10. This option is used only if you use in dateFormat two-digit year format and serves as a compensator for determining the century. If the value is provided as a number, then it is used directly. If the value is provided as a string, then it is converted to a number and added to the current year. Once the value of the cutoff year is determined, any dates, with a year value less than or equal to it are considered as of this century. Greater values - are considered as of the previous century.
  • showAnim - determines the type of animation when you open the calendar. By defaults set to show (when closing hide will be used). Without connecting additional files you can use the effects of "slideDown" and "fadeIn" (when closing, respectively, the effects of "slideUp" and "fadeout" will be used). You can also use any effects in jQuery UI Effects of course, only if you additionally connect them.
  • showButtonPanel - setting the value to true for this option will cause that the panel will display two buttons - "jump to current date" and "closing the calendar".
  • showCurrentAsPos - when displaying multi-month, the number provided to this option determines the position of the current month. The default value is 0, and the current month is displayed in the top left corner.
  • showMonthAfterYear - by default the value is set false and the header name of the month comes before the year. If set to true, name of the month will go after year.
  • showOn - by default this option is set to "focus", this makes the calendar appear when you click in the input field. Other possible values are - "button" and "both". Next to the input field a button will appear. In the case of "button", the calendar will open by clicking on the button, in the second case, by clicking on the button, as well as, by receiving focus to the input field.
  • showOptions - if you use one of the effects of jQuery UI Effects, via this option, it is possible to provide additional settings for the animation. For example: showOptions: { direction: 'up' }.
  • showOtherMonths - by default set to false. If set to true, this will display on the calendar days preceding and/or following month, which is non-selectable.
  • stepMonths - set how many months to move in the calendar when clicking on "Next" and "Previous" links. By default it's 1 month shift.
  • yearRange - control how many years to display in the drop-down list (when using the option changeYear).

Events:

  • beforeShow - here you can define the function that will be called just before the calendar is opened. The function takes as argument an object that describes the input field which the widget is working with.
  • beforeShowDay - with this option you can set the customized function which takes the selected date as an argument. The function must return an array, where the element with index equal to [0] - true or false indicates whether or not the selection of this date is possible. The element with index [1] contains the class name (-s) to display the date. The element with index [2] (optional) - the popup tooltip for the date. The function will be called for every date in the calendar if hovered over it with the mouse cursor.
  • onChangeMonthYear - here you can define the function which will be called every time you change the month or the year in the calendar. The function has three arguments. The first two arguments - are the new year and month, the third argument - datepicker object.
  • onClose - with this option you can define the function to be called if the calendar was closed without any date being selected.
  • onSelect - this option defines the function that will be called if any date is selected in the calendar.

Methods:

  • destroy - .datepicker( 'destroy' ) removes completely the functionality of the widget Datepicker. Returns the elements into pre-initialization state.
  • disable - .datepicker( 'disable' ) temporarily disables all the functionality of the widget. To re-enable it, use the method enable.
  • enable - .datepicker( 'enable' ) enables the use of all the functionality of the widget, if it was prior disabled by the method disable.
  • option - .datepicker( 'option', optionName, [value] ) by using this method you can get or set the value of any widget option after initialization.
  • dialog - .datepicker( 'dialog', dateText, [onSelect], [settings], [pos] ) opens the Datepicker in the dialog mode. In the argument dateText a date is provided, on which the calendar is opened. Other arguments are optional. In the argument OnSelect a function can be passed, which will be called when selecting a date in the calendar, in the argument settings an object can passed with new widget settings, in the argument pos - coordinated, on which a dialog field will be open. You can use the mouse events, to determine the coordinates.
  • isDisabled - .datepicker( 'isDisabled' ) the method returns true, if to the widget the method disable was used, and false if not.
  • hide - .datepicker( 'hide', [speed] ) hides the previously opened calendar.
  • show - .datepicker( 'show' ) opens the calendar.
  • getDate - .datepicker( 'getDate' ) the method returns the date which was selected in the calendar.
  • setDate - .datepicker( 'setDate', date ) method allows you to set the date in the calendar. The value of the argument date can be a string (e.g.: 25.10.1917).

 

Read also

jQuery UI. Widgets. Dialog (Windows)

jQuery UI. Widgets. Dialog (Windows)

jQuery for beginners: selectors

jQuery for beginners: selectors

jQuery for beginners: AJAX

jQuery for beginners: AJAX

jQuery for JavaScript

jQuery for JavaScript

Discussion (total 13 comments)

Keith
November 26, 2012 at 04:53 pm
Your use of the setDefaults call is incorrect. Don't use $.extend for the initial localisation back to English. Use '' for the default US English localisation.
$.datepicker.setDefaults($.datepicker.regional['']));
Use $.extend to create one parameter for setDefaults when changing to another localisation:
$.datepicker.setDefaults($.extend({changeYear: true}, $.datepicker.regional['ru']));
Administrator User
Administrator User
November 27, 2012 at 05:02 am
Thank you! I will try it. if it works I will correct the article immediately!
Stinger
December 28, 2012 at 10:09 pm
Your tutorial looks like a good place to figure out how to use the date picker widget -- much better than the official documentation. But I think you forgot to include the actual plug-in. You need a line like:
<script src="your_path/jquery.datePicker.js" type=text/javascript></script>
Next, you refer to the class ".datapicker" but I don't see this class defined anywhere. I only see the id #datepicker. So your function does not seem to work. I cannot get the widget to display after clicking on the empty text box.

Perhaps I am missing something here? If so, my apologies in advance. Your feedback is welcome.
Administrator User
Administrator User
December 29, 2012 at 02:14 am
Thank you. I am always glad to answer on any questions and help.
To include plug-in, you need to add jQuery UI file which can be built and downloaded from: http://jqueryui.com/download/. HTML will be like this:
<script src="your_path/jquery-ui-1.9.1.custom.min.js" type="text/javascript"></script>
And two thing are required:
1. When you build jQuery UI on the site, you need to check the checkbox "Datepicker" in "Widgets" section.
2. Styles and jQuery core file should be also included before jQuery UI.
It's shown in the beginning of the article.

After these steps Datepicker will be availabe like this:
$("#datepicker").datepicker();
Where $("#datepicker") is the selector for input tag.
Here is workable example:
HTML:
<input class="calendar" type="text" />
JS:
jQuery( document ).ready( function() {
    jQuery( 'input.calendar' ).datepicker();
});
surendra
April 02, 2013 at 03:50 am
in year dropdown box it is showing past 20years every time but i want 50 past years
Administrator User
Administrator User
April 02, 2013 at 05:04 am
The following code does it:
jQuery.datepicker.setDefaults({ yearRange: '1963:2013' });
Andre
April 18, 2013 at 03:37 pm
Hello everyone! I'm having some trouble using jquery's datepicker, I'm new in programming so I really hope you can help 'cause I'm getting really frustrated with this...I'm trying to use the datepicker in xampp but I have no idea where to extract the files I downloaded and haven't found any step by step tutorial, I'm trying to use datepicker in portuguese.

thanks in advance
Anton Muchychka
Anton Muchychka
April 24, 2013 at 05:25 am
I have tried below configuration and it's working fine on my local host -
Browser Tested - Mozilla Firefox version 3.6.10
I have xampp package installed.

....just install firebug ( an addon for mozilla) in your firefox browser. Just check in firebug's console that are you getting any js errors.
David Walker
August 24, 2013 at 09:55 pm
How do you post this via form?
Benson
January 30, 2014 at 04:11 am
How can one format the value of the date picker, say, for example: 2014-01-30.

Thanks.
Administrator User
Administrator User
January 31, 2014 at 03:14 pm
Just initialize the datepicker by the following code:
$( '#datepicker' ).datepicker({ dateFormat: 'yy-mm-dd' });
Ankur
February 25, 2014 at 05:08 am
Good Tutorial as compared to the official documentation.But i need one modification help.how can i change the height and width of the datepicker box that appears on focussing the textbox?.i.e i am not able to find the exact location for these size definitions in the css file.

Thankyou.
Administrator User
Administrator User
February 27, 2014 at 02:43 am
There are no styles for this. But, you can add your own. To increase the width:
#ui-datepicker-div {
  width: 600px;
}
To increase the height, you need to increase padding-top and padding-bottom for the element inside each cell in the table where the calendar located. Just try to increase them and see what happens:
#ui-datepicker-div .ui-datepicker-calendar td a,
#ui-datepicker-div .ui-datepicker-calendar td span {
  padding-top: 20px;
  padding-bottom: 20px;
}

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation