2011-08-10 65 views
5

如何在jQuery datepicker之前禁用日期datepicker 沒有使用minDate: 0如何在今天之前在jQuery中禁用日期datepicker

我想在今天之前按照慣例啓用日曆的導航,同時確保用戶在今天之前不選擇日期。

(即說今天的日期是11Aug11,我想這個禁止,但仍允許用戶之前所有的日期要到前幾個月,幾年,等)

+6

從UX的角度來看,爲什麼你會希望他們能夠看到* *,而不能選擇* *值的數值? – zzzzBov

+0

謝謝你們,我確實認爲它看起來多餘,但我正在建立一個網站,允許客戶安排會議/活動。以防萬一,客戶可以更方便地查看同一日曆中的以前日期。 – user864600

回答

6

雖然我同意這是奇怪的行爲,但您也許可以使用datepicker的onSelect事件來僞造它。

$(document).ready(function() { 
    $('#Date').datepicker({ 
     onSelect: function(dateText, inst) { 
      //Get today's date at midnight 
      var today = new Date(); 
      today = Date.parse(today.getMonth()+1+'/'+today.getDate()+'/'+today.getFullYear()); 
      //Get the selected date (also at midnight) 
      var selDate = Date.parse(dateText); 

      if(selDate < today) { 
       //If the selected date was before today, continue to show the datepicker 
       $('#Date').val(''); 
       $(inst).datepicker('show'); 
      } 
     } 
    }); 
}); 

基本上,你處理onSelect事件。

選擇一個日期時,檢查它是否在今天的日期之前。

如果它,那麼你立即show datepicker再次清除附加到它的輸入框。


更新 代碼示例現在完全有功能的。這裏有一個jsfiddle來演示。

1

它不會出現是可配置的。在line 1434 of jquery.ui.datepicker.js,如果指定了maxDate,它將設置一個maxDraw變量並繪製到該日期的月份,而不考慮任何其他標誌。

但我也同意zzzzBov。爲什麼用戶需要查看他們無法選擇的值?

3

希望這對某人仍然有幫助。 我的解決辦法是把對個別日期的檢查是這樣的:

$("#StartDate").datepicker({ dateFormat: 'yy-mm-dd', beforeShowDay: NotBeforeToday}); 



function NotBeforeToday(date) 
{ 
    var now = new Date();//this gets the current date and time 
    if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() > now.getDate()) 
     return [true]; 
    if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth()) 
     return [true]; 
    if (date.getFullYear() > now.getFullYear()) 
     return [true]; 
    return [false]; 
} 

我覺得它簡潔大方

1

相反,你可以寫在你的.js函數文件中像這個 -

$(function() { 

      var date = new Date(); 
      var currentMonth = date.getMonth(); 
      var currentDate = date.getDate(); 
      var currentYear = date.getFullYear(); 

      if($("#dateToSelect").length > 0){ 
       $("#dateToSelect").datepicker({ 
       maxDate: new Date(currentYear, currentMonth, currentDate) 
      }); 
      } 
}) 

這裏「dateToSelect」是顯示日期的字段的ID。這裏檢查日期長度不是強制性的。

1

最簡單的解決辦法....

<script type="text/javascript">$('#date').datepicker({ minDate: 0 });</script> 
相關問題