我正在尝试设置月,日输入
为此,我有2个字段第1个 A DropDownList
,允许用户选择month
。
<asp:DropDownList ID="month" runat="server" onchange="refSelect();"></asp:DropDownList>
第二名:select
,允许用户选择day
<select ID="day" runat="server"></select>
每当用户更改month
时,JavaScript函数都会更新您可以在day
字段中选择的日期。
month
和day
字段的选项都加载在page_load
后面的代码中
我遇到的问题是,无论何时加载页面并将month
字段设置为(例如2月),用户都会更改为1月的另一个月,并选择一天> 28
代码后面将所选日期保存为1.
int test = day.Value; //test will equal 1
如果用户选择任何一天<= 28
,则后面的代码会保存他们选择的任何内容。 JavaScript
:
var Months = {
"January": function () { return 31; },
"February": function () { return 28; },
"March": function () { return 31; },
"April": function () { return 30; },
"May": function () { return 31; },
"June": function () { return 30; },
"July": function () { return 31; },
"August": function () { return 31; },
"September": function () { return 30; },
"October": function () { return 31; },
"November": function () { return 30; },
"December": function () { return 31; }
}
refSelect: function () {
var month = document.getElementById("month");
var day = document.getElementById("day");
var monthSelected = month.options[month.selectedIndex].text;
daysTotal = Months[monthSelected]();
if (day.options.length > daysTotal) {
day.options.length = daysTotal;
}
else if(day.options.length < daysTotal) {
while (day.options.length < daysTotal) {
var option = document.createElement('option');
option.text = option.value = day.options.length + 1;
day.add(option);
day.options[day.options.length] = option;
}
}
有谁知道如何防止这种情况发生?
代码背后:
//redirects to another page after executing
protected void btnSave_Click(object sender, EventArgs e)
{
int month = (DropDownList)Page.FindControl("month").SelectedValue;
int day= (HtmlSelect)Page.FindControl("day").Value;
string monthDay = String.Format("{0}/{1}", month, day);
User.SaveSelectedDate(monthDay);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDropDowns();
}
}
private void LoadDropDowns()
{
string saved = User.GetSavedDate();
DropDownList month = (DropDownList)Page.FindControl("month");
HtmlSelect day= (HtmlSelect)Page.FindControl("day");
string[] split = saved.Split('/');
DateTime start = new DateTime(1, 1, 1);
for (int j = 0; j < 12; j++)
{
DateTime current = start.AddMonths(j);
month.Items.Add(new ListItem(String.Format("{0:MMMM}", current), current.Month.ToString()));
}
month.SelectedValue = split[0];
for (int d = 1; d <= DateTime.DaysInMonth(1, Int32.Parse(month.SelectedValue)); d++)
{
day.Items.Add(new ListItem(d.ToString(), d.ToString()));
}
day.Value = Int32.Parse(split[1]);
}