I have these select boxes as follow:
<?php
echo'
<select id="months"></select>
<select id="days"></select>
<select id="years"></select>
'; ?>
I want the options for each select boxes to be the current date to be automatically selected on load. Like for example today(January 28, 2016): the first select box should have January selected. and the next one should be 18, and the last 1 should be 2016.
Actually I already got that working for the days
select box with this code.
for ($x = 1; $x <= 31; $x++) {
echo '<option value="'.$x.'" ';
if ($x == date_format($nowdate,'d'))
{
echo 'selected';
}
echo' >'.$x.'</option>';
}
But I don't know how to do it on months
. And 1 more problem, I want when months
changes, the days
should also change its options depending on the number of days the selected month has. Any help would be greatly appreciated. Thanks.
Consider 2000-3000 as options included for years
Select box
You can try the below code for populating months :
for ($x = 1; $x <= 12; $x++) {
$mon = date('F', mktime(0,0,0,$x));
echo '<option value="'.$mon.'" ';
if ($mon == date('F'))
{
echo 'selected';
}
echo' >'.$mon.'</option>';
}
Same way, you can use date('Y') to figure out the current year.
For the JavaScript part, you can use the following code -
Onchange of months select box call the following function and pass two parameters (current selected month and selected year) -
function getCurrentdays(month,year) {
var currentdays = new Date(year, month, 0).getDate();
populatedayscombo(currentdays);
}
function populatedayscombo(currentdays)
{
document.getElementById("monthscombo").options.length = 0;
for (x = 1; x <= currentdays; x++)
{
var newOption = document.createElement("option");
newOption.text = x;
newOption.value = x;
document.getElementById("monthscombo").add(newOption);
}
}