Displaying number of days in form field depending on month
I want to validate the basic date format in the form. The date has three fields in form, Month, Day and Year. I want to make it so that, if a month January, March, May, July, August, October or December is selected then it 开发者_JAVA技巧should display 31 days in the day field. If february is selected, then it should display 28 days, otherwise 30 days. Also, If someone selects day before the month and then selects the month, then it should reset the selected day to 1. Here's my form code. I shall be very thankful for any help.
<?php
$monthOptions = '';
$dayOptions = '';
$yearOptions = '';
for($month=1; $month<=12; $month++){
$monthName = date("M", mktime(0, 0, 0, $month));
$monthOptions .= "<option value=\"$month\">$monthName</option>\n";
}
for($day=1; $day<=31; $day++){
$dayOptions .= "<option value=\"$day\">$day</option>\n";
}
for($year=1900; $year<=2010; $year++){
$yearOptions .= "<option value=\"$year\">$year</option>\n";
}
?>
<html>
<body>
Select date:<br />
<select name="month" id="month" >
<?php echo $monthOptions; ?>
</select>
<select name="day" id="day">
<?php echo $dayOptions; ?>
</select>
<select name="year" id="year" >
<?php echo $yearOptions; ?>
</select>
</body>
</html>
I sort of hate to suggest adding another JS library to your project, but since you're already using jQuery, I'm going to point you toward jQuery UI - particularly, jQuery UI Datepicker. It'll take care of all those finicky date issues for you (I hate working with dates and times - there are so many gotchas). The user will click on the input (or a datepicker button), and they'll pick the date by clicking it on a calendar (or they can type it into the input directly). You'll get the date back in a single input rather than three, but it's readily parsable by Date.parse (or the PHP equivalent) if you need finer-grained whatever.
Disclaimer: It's a little annoying to use if the date can be over a number of years. There are arrows to change the month on the calendar widget, but none for the year. There are keyboard shortcuts (Ctrl + PgUp / PgDown), but there's no way of knowing that without reading the docs, so you might want to make a note by the input if you go this way. There might be a way to add year buttons in, too, but I sure haven't found it...
Hope this helps!
精彩评论