Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Create Self-updating Form Fields for Date Selection

The code from the following phrase 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.

<?php
 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, 
    $year));
  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";
  }
 ?></select>
 // ...
</form>

The Date Selection Updates Itself Automatically (dateselection-js.php; excerpt)

Figure 3.4

Figure 3.4 The month names were automatically generated.

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 Chapter 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 phrase 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. Figure 3.5 contains the output of the complete code.

  • + Share This
  • 🔖 Save To Your Account