Keywords: jQuery UI | Datepicker | yearRange | year dropdown | configuration
Abstract: This article explains how to use the yearRange option in jQuery UI Datepicker to set the initial range of the year dropdown to 100 years, addressing the default display of only 10 years. It covers the syntax, code examples, and related configurations, providing a comprehensive guide for developers.
Introduction
jQuery UI Datepicker is a versatile plugin that allows users to select dates from a calendar. By default, when the changeYear option is enabled, the year dropdown displays a range of 10 years relative to the current year or the selected year. However, in many applications, a broader range is required for better user experience.
Problem Description
The default year range in the Datepicker dropdown is set to "c-10:c+10", meaning it shows 10 years before and after the current year or selected year. This limited range forces users to repeatedly click to view more years, which can be inefficient.
Solution
To address this, the yearRange option can be used to specify a custom range. This option accepts various formats, including absolute years (e.g., "1950:2013") or relative years (e.g., "-100:+0" for the last 100 years). It is important to note that yearRange only affects the dropdown display; to restrict selectable dates, minDate and maxDate options should be used.
Code Example
Here is an example of how to initialize the Datepicker with a year range of 100 years:
function initDatePickers() {
$(".datepicker").datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
yearRange: "-100:+0", // Sets the range to last 100 years
maxDate: "+0d", // Example: no future dates
minDate: "-100y" // Example: dates from 100 years ago
});
}In this code, the yearRange is set to "-100:+0", which displays years from 100 years ago to the current year. The minDate and maxDate are set accordingly to match the range, but they are optional and serve different purposes.
Detailed Explanation
The yearRange option supports multiple formats:
- Relative to today: e.g., "-nn:+nn"
- Relative to current selection: e.g., "c-nn:c+nn"
- Absolute: e.g., "1900:2020"
- Combinations: e.g., "1900:-10"
From the jQuery UI documentation, the default is "c-10:c+10". This option is part of the extensive customization available in Datepicker, which includes other features like localization, theming, and keyboard navigation.
Conclusion
By utilizing the yearRange option, developers can easily extend the year dropdown in jQuery UI Datepicker to display a larger range of years, such as 100 years, enhancing usability without additional user interaction. This simple configuration improves the overall user experience in date selection tasks.