You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS设置HTML date输入框max属性不生效 固定值可生效问题求解

问题原因

HTML 原生 type="date" 输入框的 max 属性仅支持 YYYY-MM-DD 格式的字符串值。你直接将 Date 对象传入 setAttribute 时,Date 对象会被默认转换为 Tue Sep 12 2023 00:00:00 GMT+0800 (中国标准时间) 这类长文本格式,完全不符合属性的格式要求,因此设置不生效。你之前传入固定的 '2021-10-31' 符合格式要求,所以可以正常生效。

修复方法

你需要将计算得到的 Date 对象手动格式化为 YYYY-MM-DD 格式的字符串后再赋值给 max 属性,修正后的代码如下:

// Declare values for use in functions
let dateInput = document.getElementById("dateInput");
var endDateInput = document.getElementById("end_date");

// Shows the end date field
function showEndDate() {
  var inputValue = dateInput.value;
  var inputDate = new Date(inputValue);
  if(inputValue != "") {
    document.getElementById("panel").style.display = "block";
  } else {
    alert("Date cannot be blank");
    return; // 空日期直接终止后续逻辑
  }
  inputDate.setDate(inputDate.getDate() + 21);
  console.log(inputDate);
  // 手动格式化为YYYY-MM-DD格式
  const year = inputDate.getFullYear();
  const month = String(inputDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数,补前导零
  const day = String(inputDate.getDate()).padStart(2, '0'); // 日期补前导零
  const maxDateStr = `${year}-${month}-${day}`;
  endDateInput.setAttribute("max", maxDateStr);
}

内容的提问来源于stack exchange,提问作者Jeanclaude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:45:03