Create Year Picker Widget From jQuery-UI Date Picker

jQuery-ui is a famous front-end framework from the jQuery team. It offers a lot of widgets like Date picker, button, dialog, progress bar, etc. But, it does not have Year Picker. Here, I have explained how to create a year picker from the date picker widget.

How to do

Create two input fields. One is hidden (actually date picker) and another one is an actual input field that shows year value. When we focus on actual input field, the hidden field shows date picker under the actual field.

1. Add jQuery and jQuery-ui libraries.

  1.  <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />  
  2. <script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>  
  3. <script src="~/Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>  

 

2. Hide date picker element and month label

Set .ui-datepicker-calendar, .ui-datepicker-month { display:none !important;}.

3. Offset Of DatePicker:

Adjust the height of datepicker that depends on your actual input field.

div#ui-datepicker-div { margin-top: 41px; }

  1. <style type="text/css">  
  2.     .ui-datepicker-calendar,  
  3.     .ui-datepicker-month {  
  4.         display: none !important;  
  5.     }  
  6.   
  7.     div#ui-datepicker-div {  
  8.         margin-top: 41px;  
  9.         /*adjust this value depend on input field height*/  
  10.     }  
  11. </style> 

 

 4. Actual and duplicate fields of date pickers.
  1. <form name="yearform" id="yearform"> <input type="hidden" id="dummyseason" name="dummyseason" />  
  2.     <!-- actual datepicker but duplicate input --><input type="text" autocomplete="off" class="form-control" id="Year" name="Year" />  
  3.     <!-- actual input but duplicate datepicker-->  
  4.     </br> <button type="submit">Submit</button>   
  5. </form>  

5. Invoke Year Picker when focus on “Year” field using ‘$("#Year").focus()’ event.

6. ‘stepMonths: 12’ property can skip month to year when click left and right arrow of date picker.

7. Set selected year to actual field (‘name=Year’) using onChangeMonthYear method.

  1. <script type="text/javascript">  
  2.     $("#Year").focus(function(e) { //invoke real datepicker with duplicate  
  3.         $("#dummyseason").datepicker('show');  
  4.     });  
  5.     $("#dummyseason").datepicker({  
  6.         stepMonths: 12,  
  7.         yearRange: "c-10:c+20",  
  8.         showButtonPanel: true,  
  9.         changeYear: true,  
  10.         dateFormat: 'mm/dd/yy',  
  11.         onChangeMonthYear: function(year, month, obj) {  
  12.             $("#Year").val(year); //set YEAR value TO real input  
  13.             $("#dummyseason").val(month.toString().concat("/01/", year)); //set full date to REAL daTEPIC  
  14.         },  
  15.     });  
  16. </script>  

 

 

Summary

jQuery-ui is a perfect UI tool for web applications. We can extend the features of jQuery-ui with little efforts.