How To Restrict Year In Jquery Datepicker

jQuery UI’s DatePicker is a powerful and easy-to-use datepicker widget that allows users to select dates from a calendar. One common requirement is to restrict the range of selectable years in the datepicker. In this blog post, we will learn how to restrict the year range in a jQuery DatePicker.

Prerequisites

Before we begin, make sure that you have the following libraries included in your HTML file:

  • jQuery
  • jQuery UI

Include these libraries by adding the following lines to the head section of your HTML file:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Restricting the Year Range

To restrict the year range in the jQuery DatePicker, we can use the yearRange option. The yearRange option can be set as a string in the format “start:end”, where start and end are the starting and ending years of the selectable range.

For example, to restrict the year range from 2000 to 2020, we can set the yearRange option as follows:

$(document).ready(function () {
$(“#datepicker”).datepicker({
yearRange: “2000:2020”
});
});

Here’s a complete example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery DatePicker Year Restriction Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>

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

    <script>
        $(document).ready(function () {
            $("#datepicker").datepicker({
                yearRange: "2000:2020"
            });
        });
    </script>
</body>

</html>

In this example, we have an input element with an ID of datepicker. We then initialize the jQuery DatePicker on that element and restrict the year range to 2000 – 2020 using the yearRange option.

Conclusion

In this blog post, we have learned how to restrict the year range in a jQuery DatePicker using the yearRange option. This can be useful to limit the selection of dates based on specific requirements or business rules. You can explore more options and features of the jQuery DatePicker in the official documentation.