Datepicker | jQuery UI

Datepicker | jQuery UI

4 1390

Full calendar datepicker. If you are not familiar with jquery ui, and you are looking for a way to add a datepicker to your website, it would be superfluous to read this article, where we will tell how to add and configure datepicker. It’s easy enough if you are already familiar with this library, but it will be very useful for beginners. This tutorial is also provided by several illustrative examples which you can try online.



First at all, you can download jQuery UI library here. Now, you can prepare an empty HTML file and add next code:

    <!-- add styles -->
    <link href="css/ui-lightness/jquery-ui-1.9.2.custom.min.css" rel="stylesheet" type="text/css" />

    <!-- add scripts -->
    <script src="js/jquery.191.js"></script>
    <script src="js/jquery-ui-1.9.2.custom.min.js"></script>

Please pay attention, that you will need to put all the files of jQuery UI to appropriate folders (let’s keep all JS files in ‘js’ folder and all CSS in ‘css’ folder). Well, we have just linked all the necessary libraries and styles. Now, in order to add a calendar, we need to add a single line:

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

It is also possible to add this as an inline-object. In this case we don’t need to specify ‘type’ param:

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

Finally, to complete this page and to initialize our datepicker, let’s add some JS code:

<script>
$(function(){
  $.datepicker.setDefaults(
    $.extend($.datepicker.regional[''])
  );
  $('#datepicker').datepicker();
});
</script>
Live Demo 1

By default, the main interface is in English. But, you easily can change it via options, let’s say – German interface:

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

We also can modify another params, for instance minDate and maxDate:

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

Events

This is an example how you can add your events:

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

There are three event handlers: beforeShow – this function is triggered before the calendar is shown. With the help of css-option the INPUT will be set to yellow background. onSelect is triggered when you select a date, it alerts the selected date (with other params) and nullifies the value of background-color. onClose function is triggered when we have closed the calendar.


Methods

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

This example demonstrates the dialog method. When we click on the link, it invokes the function. The first argument is the name of the method, the second argument textDate – the default date on which the calendar opens. In the argument onSelect we can set callback-function which will be invoked when you have selected a certain date in the calendar. In the argument settings you can define an object with the new widget settings that could be applied to the calendar.


Datepicker 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).
Published at Script Tutorials with permission of BASICuse (source)

SIMILAR ARTICLES

Practice with Text Shadows

0 376
Responsive HTML Email Template

0 589

4 COMMENTS

  1. Hello,
    So I followed the steps of the tutorial, I put the files in the right folder paths.
    When I run my page, I have this javascript error:

    TypeError: $ datepicker is undefined.
    $. datepicker.setDefaults (

    … and thank you for the tutorial :)

Leave a Reply