I have 3 html <select> the year, month, and day. Both the year and month automatically sets to the current year and current month. I did that purely in PHP. However, the day which is being triggered by Javascript doesn’t seem to work even though I already did
if (j == <?php echo date('d') ?>) days_select.options[days_select.options.length] = new Option(j, j, true);
The default day is still 1 not the current day. What is even frustrating is that when I checked it on firebug the selected day is the current day… I am a total noob in programming that’s why simple things like these are kinda hard for me to grasp. Pls help…
date_select.php
<body onload="loadDays();">
<script type="text/javascript" >
function loadDays() {
var year = parseInt(document.getElementById('years').value);
var month = document.getElementById('months').value;
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var days = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
if ((year % 4) == 0) days[1] = 29;
var days_select = document.getElementById('days');
days_select.options.length = 0;
for(i in months) {
if (month == months[i]) {
for(var j = 1; j <= days[i]; j++ ) {
if (j == <?php echo date('d') ?>) days_select.options[days_select.options.length] = new Option(j, j, true);
else days_select.options[days_select.options.length] = new Option(j, j);
}
break;
}
}
}
</script>
<span style="display: table; ">
<span style="display: table-cell; ">
<select id="years" onchange="loadDays();">
<?php
for($year = 1900; $year <= 2100; $year++ ) {
if ($year == date('Y')) echo "<option value='$year' selected=''>" . $year . "</option>";
else echo "<option value='$year'>" . $year . "</option>";
}
?>
</select>
</span>
<span style="display: table-cell; ">
<select id="months" onchange="loadDays();">
<?php
$months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" );
foreach($months as $month){
if ($month == date('M')) echo "<option value='$month' selected=''> " . $month . "</option>";
else echo "<option value='$month'> " . $month . "</option>";
}
?>
</select>
</span>
<span style="display: table-cell; ">
<select id="days" >
</select>
</span>
</span>
</body>
I’m putting this in as a separate answer since it, well, is one.
The third parameter to
Option()is whether the option is selected by default, as though it were specified in HTML. The fourth is whether it is actually selected right now. Add anothertrueto yourOption()call and it works for me in testing.