年月日下拉選單的程式筆記
<script type="text/javascript" src="Scripts/jquery-1.5.1.js"></script>
<script type="text/javascript">
// 取得一個月有幾天
function getDaysInMonth(year, month) {
month = parseInt(month, 10) + 1;
var temp = new Date(year + "/" + month + "/0");
return temp.getDate();
}
// 字串左邊補零
function padLeft(str, lenght) {
if (str.length >= lenght)
return str;
else
return padLeft("0" + str, lenght);
}
// 字串右邊補零
function padRight(str, lenght) {
if (str.length >= lenght)
return str;
else
return padRight(str + "0", lenght);
}
function fillDay() {
var year = $('#<%= ddlYear.ClientID %>').find(':selected').val();
var month = $('#<%= ddlMonth.ClientID %>').find(':selected').val();
// 清空日期的下拉式選單
$('#ddlDay').html('');
// 將天數填入日期的下拉式選單
for (var i = 1; i <= getDaysInMonth(year, month) ; i++) {
var value = padLeft(i.toString(), 2);
$('#ddlDay').append(
$("<option></option>").
attr("value", value).
text(value));
}
// 用hidden裡的值,對日期作選取,這樣post後,日期的值不會跑掉
if ($('#<%= hiddenDay.ClientID %>').val().length > 0) {
$('#ddlDay').val($('#<%= hiddenDay.ClientID %>').val());
}
}
$(document).ready(function () {
fillDay();
$('#<%= ddlMonth.ClientID %>').change(function () {
fillDay();
});
$('#ddlDay').change(function () {
var day = $(this).find(':selected').val();
// 將選取的值放到 hidden 裡
$('#<%= hiddenDay.ClientID %>').val(day);
});
});
</script>
在aspx
<asp:DropDownList ID="ddlYear" Font-Size="12px" runat="server"></asp:DropDownList>年
<asp:DropDownList ID="ddlMonth" Font-Size="12px" runat="server"></asp:DropDownList>月
<select id="ddlDay"></select>日
<asp:HiddenField ID="hiddenDay" runat="server" />
在.CS
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
// Year
for (int i = 2000; i <= 2050; i++)
{
this.ddlYear.Items.Add(i.ToString());
}
// Month
for (int i = 1; i <= 12; i++)
{
this.ddlMonth.Items.Add(i.ToString("00"));
}
}