jQuery UI Datepicker is a powerful and versatile tool for selecting dates. However, sometimes you may need a more
specific date format, such as displaying the year only. In this blog post, we will guide you through the process
of customizing the jQuery Datepicker to show only the year.
Requirements
Before getting started, make sure you have included the required libraries in your project. You will need the
following:
- jQuery library
- jQuery UI library
- jQuery UI CSS (for styling the datepicker)
Include the necessary libraries in the head of your HTML file, like so:
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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.js"></script>
Customizing the Datepicker
To show only the year in the jQuery Datepicker, you will need to customize the date format and restrict the
datepicker’s view. Follow the steps below to achieve this:
Step 1: Set up an input field for the datepicker
Create an input field in your HTML file where the datepicker will be attached:
<input type="text" id="yearPicker">
Step 2: Initialize the datepicker with custom options
Initialize the datepicker on the input field you created in the previous step and set the custom options for
displaying only the year. Add the following script to your HTML file:
<script> $(document).ready(function () { $("#yearPicker").datepicker({ dateFormat: "yy", changeYear: true, changeMonth: false, showButtonPanel: true, yearRange: "1900:2100", onClose: function (dateText, inst) { var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker("setDate", new Date(parseInt(year), 1)); }, }); $("#yearPicker").focus(function () { $(".ui-datepicker-month").hide(); $(".ui-datepicker-calendar").hide(); $(".ui-datepicker-prev").hide(); $(".ui-datepicker-next").hide(); }); }); </script>
Here’s a breakdown of the custom options used in the script above:
- dateFormat: “yy” – set the date format to display only the year.
- changeYear: true – enable the year dropdown selection.
- changeMonth: false – disable the month dropdown selection.
- showButtonPanel: true – display the button panel with the “Done” button.
- yearRange: “1900:2100” – set the range of years available for selection.
Additionally, the onClose function is used to ensure that the selected year value is properly
set when the datepicker is closed. The focus event handler hides the month and calendar
elements to display only the year selection.
Conclusion
With the above customization, your jQuery Datepicker will now display only the year, allowing users to easily
select a year without any additional clutter. Remember to include the required libraries and customize the
options according to your needs for a seamless integration with your project.