/ Published in: PHP
Here is a little bit of code I use from time to time to make a generic some what safe date selector for forms. I wanted something easy, small, and not relying on images, jquery, libraries, etc... Most importantly I wanted the date that was selected to be in INT format for storing directly into the database as an INT. Mind you the point of this snippet is the function, not the example tester code.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php { } function getDateSelect( $name ) { // use today if not set. { } //$t makes it simplier to type. $t = $_POST[$name]; // make $t always midnight $r = ""; // make the js function // php generating JS YEAH! // actually not too bad just take the selector value and make a date out of it // then convert it to PHP time()/MYSQL $r .= "<script>\n"; $r .= "function update_".$name."()\n"; $r .= "{\n"; $r .= "var d=document.getElementById( '".$name."-d' ).value;\n"; $r .= "var m=document.getElementById( '".$name."-m' ).value-1;\n"; $r .= "var y=document.getElementById( '".$name."-y' ).value;\n"; $r .= "var myDate=new Date(y,m,d);\n"; $r .= "var val=Math.floor( myDate.getTime() / 1000 );\n"; $r .= "//alert( val );\n"; $r .= "document.getElementById( '".$name."' ).value = val;\n"; $r .= "}\n"; $r .= "</script>\n\n"; // make the hidden field that the selector will work on. $r .= "<input type=\"hidden\" name=\"".$name."\" id= \"".$name."\" value='".$t."' />\n"; // now make the day select $i = 0; $r .= "\n<select name=\"\" id='".$name."-d' onChange='update_".$name."();' />\n"; while( $i++ < 31 ) { $sel = ""; if( $d == $i ) { $sel = " selected "; } $r .= "<option value='".$i."'".$sel.">".$i."</option>\n"; } $r .= "</select>\n\n"; // now make the month select $i = 0; $r .= "\n<select name=\"\" id='".$name."-m' onChange='update_".$name."();' />\n"; while( $i++ < 12 ) { $sel = ""; if( $m == $i ) { $sel = " selected "; } $r .= "<option value='".$i."'".$sel.">".$i."</option>\n"; } $r .= "</select>\n\n"; // now make the year select $i = 1900; $r .= "\n<select name=\"\" id='".$name."-y' onChange='update_".$name."();' />\n"; while( $i++ < 2025 ) { $sel = ""; if( $y == $i ) { $sel = " selected "; } $r .= "<option value='".$i."'".$sel.">".$i."</option>\n"; } $r .= "</select>\n\n"; return $r; } ?> <html> <head> </head> <body> <form method="post"> <?= getDateSelect( "tester" ); ?> <br /> <input type="submit" /> </form> </body> </html>