Create Self-updating Form Fields for Date Selection

The code from the following has one minor flaw: The number of days per month is always from 1 to 31, even in months that have less days. Using JavaScript, it is possible to write a fancy script that calculates how many days the current month has and then updates the selection list.

The Date Selection Updates Itself Automatically

  if (isset($_POST['month']) && is_numeric($_POST
   ['month']) &&
    ((int)$_POST['month'] >= 1 && (int)$_POST['month'] <= 12)) {
    $month = (int)$_POST['month'];
  } else {
    $month = date('n');
  if (isset($_POST['year']) && is_numeric($_POST
   ['year']) &&
    ((int)$_POST['year'] >= 2005 &&
(int)$_POST['year'] <= 2010)) {
    $year = (int)$_POST['year'];
  } else {
  $year = date('Y');
<form method="post" action="<?php echo
   htmlspecialchars($_SERVER['PHP_SELF']); ?>">
  <select name="day"><?php
    $maxdays = date('t', mktime(12, 0, 0, $month, 1,
    for ($i = 1; $i <= $maxdays; $i++) {
      if (isset($_POST['day']) && $_POST['day'] ==
       $i) {
        $sel = ' selected';
      } elseif ($i == date('j')) {
        $sel = ' selected';
      } else {
        $sel = '';
      echo "<option value=\"$i\"$sel>$i</option>\n";
  // ...

However, it is much more convenient to use a combination of JavaScript and PHP. Using JavaScript, you automatically submit the form. Using PHP, you prefill the form fields (see tutorial 4, "Interacting with Web Forms," for more information about that) and, more importantly, find out how many days the related year has.

The JavaScript code is limited to a minimum: Selecting another month submits the HTML form (as does selecting another year because leap years make February longer):

<select name="month" onchange="this.form.submit();">
<select name="year" onchange="this.form.submit();">

The number of days per month can be found using date('t'). The listing at the beginning of This contains the complete code for this, including some sanity checks for the information transmitted. Also, the code automatically preselects the current date, unless the user chooses something else. The figure contains the output of the complete code.

The PHP code filled the month selection list with the appropriate number of days.

by BrainBellupdated