Friday, 3 June 2016

Dynamic Date Dropdown Select Menu in PHP

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.
The PHP date select function:
01function date_dropdown($year_limit = 0){
02        $html_output = '    <div id="date_select" >'."\n";
03        $html_output .= '        <label for="date_day">Date of birth:</label>'."\n";
04 
05        /*days*/
06        $html_output .= '           <select name="date_day" id="day_select">'."\n";
07            for ($day = 1; $day <= 31; $day++) {
08                $html_output .= '               <option>' . $day . '</option>'."\n";
09            }
10        $html_output .= '           </select>'."\n";
11 
12        /*months*/
13        $html_output .= '           <select name="date_month" id="month_select" >'."\n";
14        $months = array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
15            for ($month = 1; $month <= 12; $month++) {
16                $html_output .= '               <option value="' . $month . '">' . $months[$month] . '</option>'."\n";
17            }
18        $html_output .= '           </select>'."\n";
19 
20        /*years*/
21        $html_output .= '           <select name="date_year" id="year_select">'."\n";
22            for ($year = 1900; $year <= (date("Y") - $year_limit); $year++) {
23                $html_output .= '               <option>' . $year . '</option>'."\n";
24            }
25        $html_output .= '           </select>'."\n";
26 
27        $html_output .= '   </div>'."\n";
28    return $html_output;
29}
It’s usage:
01<form action="" method="post">
02 
03<label for="name">Name:</label>
04<input type="text" name="name" />
05<?php
06echo date_dropdown();
07//or limit by age requirement
08echo date_dropdown(18);
09?>
10<input type="submit" name="submit" value="submit"/>
11</form>

2 comments:

  1. I am newbie of this PHP technology, this post helps me to know the introductory of PHP, Thanks for posting such a nice post.
    Regards,
    PHP Institutes in Chennai|PHP Training Center in Chennai

    ReplyDelete
  2. Thanks for this blog. It is very helpful to know about the PHP date function.
    PHP Course in Chennai | PHP Institutes in Chennai | PHP Training Center in Chennai

    ReplyDelete