How to load html <select> with values ​​when loading a page using javascript in PHP?

I am having trouble loading HTML <select>with values ​​whenever the page loads or refreshes.

I'm actually trying to create a date_select with 3 drop-down menus that include the year, month, and days on which when the month menu or year-menu changes, it automatically adjusts the number of days.

For example, when I selected the month of March, the days will be 31 or April, the days will be only 30.

My problem is that the first day the page loads, the day menu is empty. I tried onloadon <select>, but it did not work. I am new to programming, so I am having problems even with simple exercises. Please help.

date_select.php

<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++ ) 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>
 &nbsp;
 <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>
 &nbsp;
 <span style="display: table-cell; ">
  <select id="days" onload="loadDays();">

  </select>
 </span>
</span>
+3
3

onload body select.

<body onload="loadDays();">
+1

, , javascript , .

<span style="display: table; ">
...
</span>

<script type="text/javascript" >

 function loadDays() {
 ...
 }

 loadDays();
</script>
+3

jQuery, - javascript, javascript- .

, , DOM, javascript ( , "onload", )

jquery () javascript

$(document).ready(function(){
         //Here goes your code
});

javascript, jQuery

+3

All Articles