Show only Month and Year in only one jQuery UI DatePicker in case of Multiple DatePicker

In one of my previous post, I had posted about Show only Month and Year in jQuery UI DatePicker, but there was an issue with the code explained in that particular post. The issue was that it was applicable for all the datepickers present on the page and it is quite possible to have such behavior for one datepicker and rest of the datepickers control should work their default functionality.

Related Post:

How to do it?

To implement this, follow below steps only for that control for which you want to show Month and Year appear as Dropdown.

  • Set changeMonth and changeYear to true.
  • 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.
  • Now, here is tricky part. Use focus() and blur() event of the textbox control to hide default behavior of the datepicker. And in focus() event, set the position of "ui-datepicker-div" which is created by datepicker control itself and this holds UI for having month and year dropdown.
$(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));
      $(this).datepicker('refresh');
    },

    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));
      }
    }
  });

   $("#txtDate").focus(function () {
      $(".ui-datepicker-calendar").hide();
      $("#ui-datepicker-div").position({
          my: "center top",
          at: "center bottom",
          of: $(this)
      });
   });

   $("#txtDate").blur(function () {
     $(".ui-datepicker-calendar").hide();
   });
});

See result below

See Complete Code

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



Responsive Menu
Add more content here...