datepicker jquery year range

How to Select a Year Range in Datepicker using jQuery

If you are looking for a way to select a specific range of years in a datepicker using jQuery, there are several options available to you. The easiest way to achieve this is by using the yearRange option in jQuery UI's datepicker widget. This option allows you to specify a range of years that will be displayed in the datepicker.

Example Code

//Initialize the datepicker with a year range of 1990 to 2021
$( "#datepicker" ).datepicker({
  yearRange: "1990:2021"
});

In this example, we have initialized the datepicker with a year range of 1990 to 2021. This means that only the years between 1990 and 2021 will be displayed in the datepicker's dropdown list.

Alternatively, you can also specify a range of years using an array of numbers. This can be useful if you want to display a non-consecutive range of years in the datepicker.

Example Code

//Initialize the datepicker with a year range of 1990 to 1999 and 2010 to 2019
$( "#datepicker" ).datepicker({
  yearRange: [ '1990', '1999', '2010', '2019' ]
});

In this example, we have initialized the datepicker with a range of years from 1990 to 1999 and from 2010 to 2019. This means that only the years within these two ranges will be displayed in the datepicker's dropdown list.

Another option is to use the minDate and maxDate options to set the minimum and maximum dates that can be selected in the datepicker. This can provide more control over the date range that is available to the user.

Example Code

//Initialize the datepicker with a minimum date of January 1, 1990 and a maximum date of December 31, 2021
$( "#datepicker" ).datepicker({
  minDate: new Date(1990, 0, 1),
  maxDate: new Date(2021, 11, 31)
});

In this example, we have initialized the datepicker with a minimum date of January 1, 1990 and a maximum date of December 31, 2021. This means that the user will only be able to select a date within this range.

Overall, there are several ways to select a year range in a datepicker using jQuery. By using the yearRange, minDate, and maxDate options, you can provide a more customized user experience for your users.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe