如何在 JavaScript 日期選擇器中停用未來日期?


要停用未來日期,您需要使用 maxDate 並設定當前日期。以下為 JavaScript 程式碼 −

示例

 現場演示

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>The selected date is as follows: <input type="text" class="disableFuturedate"></p>
<script>
   $(document).ready(function () {
      var currentDate = new Date();
      $('.disableFuturedate').datepicker({
      format: 'dd/mm/yyyy',
      autoclose:true,
      endDate: "currentDate",
      maxDate: currentDate
      }).on('changeDate', function (ev) {
         $(this).datepicker('hide');
      });
      $('.disableFuturedate').keyup(function () {
         if (this.value.match(/[^0-9]/g)) {
            this.value = this.value.replace(/[^0-9^-]/g, '');
         }
      });
   });
</script>
</body>
</html>

為了執行上述程式,我已將此檔案另存為 index.html。右擊此檔案並選擇選項 使用 Live Server 開啟

輸出

此操作將在任何現代 Web 瀏覽器中自動執行 −

之後,在文字框上單擊滑鼠,它將顯示如下螢幕截圖所示的日期選擇器 −


更新時間:2020 年 7 月 14 日

13K+ 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始學習
廣告