Статьи

jQuery UI Datepicker

Если вы не знакомы с jquery ui и ищете способ добавить средство выбора даты на свой веб-сайт, было бы излишним читать эту статью, в которой мы расскажем, как добавить и настроить средство выбора даты. Это достаточно просто, если вы уже знакомы с этой библиотекой, но она будет очень полезна для начинающих. Этот урок также содержит несколько иллюстративных примеров, которые вы можете попробовать онлайн.


Прежде всего, вы можете скачать библиотеку jQuery UI здесь . Теперь вы можете подготовить пустой HTML-файл и добавить следующий код:

<!-- 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>

Обратите внимание, что вам необходимо поместить все файлы пользовательского интерфейса jQuery в соответствующие папки (давайте сохраним все файлы JS в папке «js» и все CSS в папке «css»). Ну, мы только что связали все необходимые библиотеки и стили. Теперь, чтобы добавить календарь, нам нужно добавить одну строку:

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

Также возможно добавить это как inline-объект. В этом случае нам не нужно указывать параметр type:

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

Наконец, чтобы завершить эту страницу и инициализировать наш указатель даты, давайте добавим немного кода JS:

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

Live Demo 1

По умолчанию основной интерфейс на английском языке. Но вы легко можете изменить его с помощью опций, скажем, немецкого интерфейса:

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

Live Demo 2

Мы также можем изменить другие параметры, например minDate и 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

События

Это пример того, как вы можете добавить свои события:

$.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

Существует три обработчика событий: beforeShow — эта функция запускается перед отображением календаря. С помощью опции css INPUT будет установлен на желтом фоне. onSelect срабатывает при выборе даты, он оповещает о выбранной дате (с другими параметрами) и обнуляет значение background-color. Функция onClose срабатывает, когда мы закрываем календарь.


методы

<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
все примеры в упаковке

Этот пример демонстрирует метод диалога . Когда мы нажимаем на ссылку, она вызывает функцию. Первый аргумент — это имя метода, второй аргумент textDate — дата по умолчанию, в которую открывается календарь. В аргументе onSelect мы можем установить функцию обратного вызова, которая будет вызываться, когда вы выбрали определенную дату в календаре. В настройках аргумента вы можете определить объект с новыми настройками виджета, которые можно применить к календарю.


Параметры выбора даты:

  • altField — jQuery-селектор для другого поля, которое должно обновляться при выборе даты из DatePicker. Формат даты в этом дополнительном поле устанавливается с помощью опции altFormat.
  • altFormat — формат даты, который будет использоваться для опции altField. Эти настройки позволяют пользователю видеть один формат даты, тогда как для расчетов может использоваться другой формат. Полный список форматов можно найти здесь http://docs.jquery.com/UI/Datepicker/formatDate
  • appendText — текст, который отображается после каждого поля ввода даты. Может использоваться, например, для пометки поля как требуется.
  • buttonImage — адрес всплывающего изображения кнопки, которое можно использовать для вызова календаря. Используется вместе с showOn, когда он имеет значения «кнопка» или «оба». Если текст был установлен в опции buttonText, он становится значением атрибута alt изображения и не отображается.
  • buttonImageOnly — если эта опция имеет значение true, изображение, адрес которого определен в опции buttonImage, появится не на кнопке, а само по себе и будет работать как триггер.
  • buttonText — текст, который будет отображаться на кнопке, который вы можете использовать для вызова календаря. Используется вместе с showOn, когда он имеет значения «кнопка» или «оба».
  • changeMonth — если эта опция включена путем установки значения true, это позволит выбрать месяц из выпадающего списка.
  • changeYear — если эта опция включена путем установки значения true, это позволит выбрать год из выпадающего списка.
  • closeText — эта опция используется вместе с showButtonPanel, если последний установлен в true. Значение параметра closeText определяется в файле локализации, если он используется, но это значение можно переопределить, указав его.
  • constrainInput — по умолчанию этот параметр имеет значение true и ограничивает формат даты, определенный в параметрах виджета, в поле ввода. Если вы не хотите использовать этот формат, установите для параметра значение false.
  • currentText — используется вместе с showButtonPanel, если для последнего установлено значение true. Значение параметра currentText определяется в файле локализации, если он используется, но это значение можно переопределить, указав его.
  • dateFormat — определяет формат даты. Значение параметра dateFormat определяется в файле локализации, если он используется, но это значение можно переопределить, указав его. Полный список всех форматов можно найти здесь http://docs.jquery.com/UI/Datepicker/formatDate
  • dayNames — массив, содержащий длинные названия дней недели, начиная с воскресенья. Определяется в файле локализации, если он используется, но это значение можно переопределить, указав его.
  • 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).