简体   繁体   中英

Validate the date in html drop-down list

I have three HTML drop down lists to select year, month and a date. If the selected year is equal to the current year second and third lists only show month and date up to the current date. I want to code this in javascript. Here the problem i am facing is, when the user select date or month at first how will it execute?

Example below. If month and day are selected first, they will not change unless the selected value is no longer valid. If they are not valid, they will reset to 1.

HTML

<body>
  <select name="month" id="month"></select>
  <select name="day" id="day"></select>
  <select name="year" id="year"></select>
</body>

JavaScript (w/JQuery)

<script type ="text/javascript" src="http://code.jQuery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
  var year = new Date().getFullYear();
  // load years
  for (var i=2000; i<=year; i++) $("#year").append('<option value=' + i + '>' + i + '</option>');
  // load months
  for (var i=1; i<=12; i++) $("#month").append('<option value=' + i + '>' + i + '</option>');
  // load days
  for (var i=1; i<=31; i++) $("#day").append('<option value=' + i + '>' + i + '</option>');
});

$(function() {
  $('#year').change(function() {
    var now = new Date();
    if ($('#year').val()==now.getFullYear()) {
      $('#month option').each(function() {
        if ($(this).val()>(now.getMonth()+1)) $(this).remove();
      });
    } else {
      for (var i=1; i<13; i++)
        if ($("#month option[value='" + i + "']").val()==undefined)
          $("#month").append('<option value=' + i + '>' + i + '</option>');
    }

    checkMonth();
  });

  $('#month').change(checkMonth);
});

function checkMonth() {
  var now = new Date();
  if ($('#year').val()==now.getFullYear() && $('#month').val()==(now.getMonth()+1)) {
    $('#day option').each(function() {
      if ($(this).val()>now.getDate()) $(this).remove();
    });
  } else {
    var days = 31;
    var month = $('#month').val();
    if (month==2) {
      if (($('#year').val() % 4) == 0) days = 29; // leap year
      else days = 28;
    } else if (month==2 || month==4 || month==6 || month==9 || month==11) {
      days = 30;
    }
    for (var i=1; i<32; i++)
      if (i>days)
        $("#day option[value='" + i + "']").remove();
      else if ($("#day option[value='" + i + "']").val()==undefined)
        $("#day").append('<option value=' + i + '>' + i + '</option>');
  }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM