Manchester Web Design Web Design & SEO Manchester Web Design Portfolio Get a Free Quote

We are an affordable and professional
Web Design & SEO company in Manchester.

Dynamic Date Dropdown Select Menu in PHP

Makes use of:

  • PHP
  • HTML

Use PHP to create dynamic drop down menu for date selection

Here is a snippet of PHP code to create a dynamic form field containing day, month and year selection fields.

The PHP code below consists of a simple function which you can echo from within your form to give it date fields dynamically. The year can go all the way up to the current year, or can be limited by an age requirement.

Here is an example of the HTML input this PHP code provides;

The PHP date select function:

function date_dropdown($year_limit = 0){
        $html_output = '    <div id="date_select" >'."\n";
        $html_output .= '        <label for="date_day">Date of birth:</label>'."\n";

        /*days*/
        $html_output .= '           <select name="date_day" id="day_select">'."\n";
            for ($day = 1; $day <= 31; $day++) {
                $html_output .= '               <option>' . $day . '</option>'."\n";
            }
        $html_output .= '           </select>'."\n";

        /*months*/
        $html_output .= '           <select name="date_month" id="month_select" >'."\n";
        $months = array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
            for ($month = 1; $month <= 12; $month++) {
                $html_output .= '               <option value="' . $month . '">' . $months[$month] . '</option>'."\n";
            }
        $html_output .= '           </select>'."\n";

        /*years*/
        $html_output .= '           <select name="date_year" id="year_select">'."\n";
            for ($year = 1900; $year <= (date("Y") - $year_limit); $year++) {
                $html_output .= '               <option>' . $year . '</option>'."\n";
            }
        $html_output .= '           </select>'."\n";

        $html_output .= '   </div>'."\n";
    return $html_output;
}

It’s usage:

<form action="" method="post">

<label for="name">Name:</label>
<input type="text" name="name" />
<?php
echo date_dropdown();
//or limit by age requirement
echo date_dropdown(18);
?>
<input type="submit" name="submit" value="submit"/>
</form>
This entry was posted in Web Development and tagged , . Bookmark the permalink.

Comments are closed.

A Rija Group site

Switch to our mobile site