表單中常需要使用者輸入日期。若只給一個空文字框,就得額外寫驗證來確認格式是否合法,使用者體驗也不好。jQuery UI 的 datepicker 外掛直接提供日曆面板,這個問題迎刃而解。
jquery-1.7.1.min.js jquery-ui-1.8.18.custom.min.js jquery.ui.core.js jquery.ui.widget.js jquery.ui.datepicker.js jquery.ui.datepicker-zh-CN.js /* 中文化所需 */ jquery-ui-1.8.18.custom.css
<input type="text" id="datepicker">
<script>
$(document).ready(function(){
$("#datepicker").datepicker();
});
</script>
做日期區間時,起日的最大值應等於迄日的最小值,反之亦然,這要靠 onSelect 完成:
var dates = $("#dep,#end").datepicker({
changeMonth: true,
changeYear: false,
showButtonPanel: true,
closeText: "關閉",
dateFormat: "yy-mm-dd",
defaultDate: "-3",
showAnim: "slide",
showWeek: true,
firstDay: 1,
yearRange: "2011:2012",
prevText: "上一月",
nextText: "下一月",
numberOfMonths: 1,
showOn: "button",
buttonText: "選擇日期",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
showOtherMonths: true,
selectOtherMonths: false,
onSelect: function(selectedDate) {
// 依目前是哪個欄位,決定要設定 minDate 還是 maxDate
var option = this.id == "dep" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
引入 jquery.ui.datepicker-zh-CN.js 之後,再宣告一次預設值即可:
$.datepicker.setDefaults($.datepicker.regional["zh-CN"]);
這一行會把月份、星期與按鈕文字一次換成中文,比逐項設定來得乾淨。