2011年5月10日 星期二

jQuery UI datepicker 1.8.12 日期輸入限制

jQuery UI datepicker 很方便的讓一個input element 可以有calendar做為協助輸入的ui,不過有時候,要validate 輸入的日期資料時,理想的方式之一就是不要讓不想輸入的資料出現。
舉例來說,如果只想讓使用者輸入 星期一 的日期,其它的日期都不要出現的話。該怎麼做?



在初使化 datepicker 時,可以設定
$('.selector').datepicker({
   beforeShowDay: function(date) { ... }
});
注意:這個設定只能在初始化的時候做,之後就不能在改變。


function(date)
The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, [1] equal to a CSS class name(s) or '' for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the datepicker before it is displayed.

說明:呼叫 function時,會傳入date參數,且必定回傳一陣列,[0] 是 true/false 型態,用來決定該date是否為可選擇的狀態,[1]是放CSS class name(s)或是'' 空字串表示預設的方式呈現,[2]是一個optional  的提示字串。每個 datepicker 上的 date 在顯示之前都會呼叫此 function 。

example: 只有星期一和星期四是 selectable (getDay() 是 javascript Date的 方法,會回傳 0~6,表示星期天 ~星期六 )

beforeShowDay: function(date){ 
  var day = date.getDay(); 
  return [day == 1 || day == 4,""];
}

所以可以使用這個fucntion 來自訂,想要設定為可以被選擇的日期,就回傳true
reference:
http://jqueryui.com/demos/datepicker/#event-beforeShowDay
http://forum.jquery.com/topic/datepicker-inline-not-working-with-beforeshowday
http://stackoverflow.com/questions/3805486/jquery-datepicker-only-select-mondays-and-thursdays

沒有留言: