【问题标题】:Validate the date in html drop-down list验证 html 下拉列表中的日期
【发布时间】:2015-07-22 20:58:38
【问题描述】:

我有三个 HTML 下拉列表来选择年、月和日期。如果所选年份等于当前年份,则第二个和第三个列表仅显示当前日期的月份和日期。 我想用javascript对此进行编码。 这里我面临的问题是,当用户首先选择日期或月份时,它将如何执行?

【问题讨论】:

  • 发布您的代码,有人可以帮助您
  • 我认为你必须限制日期范围。如果您给出更好的解释,那么我可以提供帮助。最好做个小提琴
  • 代码说的不仅仅是文字..发布您的代码

标签: javascript html validation date


【解决方案1】:

【讨论】:

  • 那个例子甚至都不正确。它允许您选择任何一年的 2 月 30 日,并且永远不允许您选择任何月份的 31 日
【解决方案2】:

示例如下。如果首先选择月份和日期,则它们不会更改,除非所选值不再有效。如果它们无效,它们将重置为 1。

HTML

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

JavaScript(带 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2016-07-11
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多