Tuesday, June 5, 2012

Show only Month and Year in jQuery UI DatePicker

jQuery UI Datepicker is a great control. The default behavior of the control shows dates along with Month and Year. But today for my requirement, I need to show only Month and Year as dropdown (with no dates). So when datepicker control is opened there should be only Month and Year dropdown. This was a bit challenging but after sometime I was able to achieve this.


How to do it?


First of all, hide the calendar area with dates. This can be done by setting "display:none" to ".ui-datepicker-calendar" CSS class. This class is responsible for styling the Date part area of the Calendar.
.ui-datepicker-calendar {
    display: none;
}​
Now,
  • Set changeMonth and changeYear to true so that Month and Year appear as Dropdown.
  • Set date format to "MM yy".
  • jQuery DatePicker has "onClose" event, which is called when Datepicker gets closed. So using this event, fetch the selected Month and Year and setDate of Datepicker.
  • jQuery DatePicker also has "beforeShow" event, which is called before the datepicker is displayed. So this event will be used to Show the previously selected Month and Year as selected. If you don't use this event, then datepicker will always show the current month and current year, irrespective of your previous selection.
$(document).ready(function() {
   $('#txtDate').datepicker({
     changeMonth: true,
     changeYear: true,
     dateFormat: 'MM yy',

     onClose: function() {
        var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
     },

     beforeShow: function() {
       if ((selDate = $(this).val()).length > 0) 
       {
          iYear = selDate.substring(selDate.length - 4, selDate.length);
          iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), 
                   $(this).datepicker('option', 'monthNames'));
          $(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
          $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
       }
    }
  });
});​
See result below.



If you want to show the buttonPanel as well (see below image) then set "showButtonPanel: true" in DatePicker options.


Feel free to contact me for any help related to jQuery, I will gladly help you.