2012-09-22 200 views
0

我正在使用jQuery DatePicker UI。我需要僅使用此UI顯示月份和年份。 我明白了用下面的代碼:JQuery日期選擇器僅適用於月份和年份

$(function() { 
     $('.date-picker').datepicker({ 
     changeMonth: true, 
     changeYear: true, 
     showButtonPanel: true, 
     dateFormat: 'yy-mm', 
     onChangeMonthYear: function(dateText, inst) { 
      var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); 
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); 
      $(this).datepicker('setDate', new Date(year, month, 1)); 

     } 
    }); 
}); 

HTML:

<input type='text' id='date' name='eattdate' class='date-picker' value='".$date."' style='width:105px;'> 

這工作正常,並顯示當前月份和年份爲default.But我要讓月份和年份選擇。

回答

0

首先,我相信你缺少日曆的隱藏(我猜你想要的,因爲你只對付幾個月甚至幾年,但我可能是錯的)。因此,如果這確實是您的意圖,請使用:

.ui-datepicker-calendar { 
    display: none; 
} 

在您的CSS文件中。現在

,作爲在日期選擇器先前選擇的日期沒有打開,你可以引入一個beforeShow,如下:

$(function() { 
    $('.date-picker').datepicker({ 
     changeMonth: true, 
     changeYear: true, 
     showButtonPanel: true, 
     dateFormat: 'yy-mm', 

     onChangeMonthYear: function(dateText, inst) { 
      var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); 
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); 

      $(this).datepicker('setDate', new Date(year, month, 1)); 
     }, 

     beforeShow: function() { 
      var dateText = $(this).val(); 
      var isPopulated = dateText.length > 0; 

      if (isPopulated) { 
       var selectedDate = $.datepicker.parseDate("yy-mm-dd", dateText + "-01"); 

       $(this).datepicker("option", "defaultDate", selectedDate); 
       $(this).datepicker("setDate", selectedDate); 
       $(this).datepicker("refresh"); 
      } 
     } 
    }); 
}); 

我相信這應該得到你想要的東西。

相關問題