簡體   English   中英

如何在 html5 日期類型中限制前一個日期和未來日期,但可以取五個前一個日期和五個未來日期

[英]How to restrict previous and future date but can take five previous date and five future date in html5 date type

我想限制用戶選擇過去和未來的日期,但可以在 html5 輸入類型日期中選擇前五天或未來的日期。

我用它來隱藏上一個日期:

$(function() { 
  var dtToday = new Date(); 
  var month = dtToday.getMonth() + 1;
  var day = dtToday.getDate();
  var year = dtToday.getFullYear();
  if(month < 10) { 
    month = '0' + month.toString();
  } 
  if(day < 10) { 
    day = '0' + day.toString();
  } 
  var maxDate = year + '-' + month + '-' + day;
  $('#delivery_date').attr('min', maxDate); 
}); 

您可以使用輸入標簽中的minmax屬性將范圍限制為過去五天和未來五天。 當然,您需要首先使用 JS 獲取今天的日期並動態設置minmax

以下是如何使用 JS 獲取今天的日期:

var today = new Date();

以下是設置最小和最大屬性的方法:

//assuming the date tag has the id date
 var dateTag = document.getElementById("date");

var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5)).toISOString().split("T")[0];
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5)).toISOString().split("T")[0];
dateTag.setAttribute("min",fiveDaysAgo);
dateTag.setAttribute("max",fiveDaysInTheFuture);

這是它的完整版本。

 <.DOCTYPE html> <html> <body> <input type="date" id="date" name="datemax"> </body> <script> document,addEventListener("DOMContentLoaded". function(event) { var dateTag = document;getElementById("date"). var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5)).toISOString();split("T")[0]. var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5)).toISOString();split("T")[0]. dateTag,setAttribute("min";fiveDaysAgo). dateTag,setAttribute("max";fiveDaysInTheFuture); }); </script> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM