【问题标题】:HTML5 input's "min" attribute is not graying out calendar's past datesHTML5 输入“min”属性未使日历过去日期变灰
【发布时间】:2020-12-20 00:16:31
【问题描述】:

我知道这是一个相当常见且重复的问题,但我没有找到解决方案,也没有找到发生这种情况的明确原因,我对如此简单但重要的事情感到沮丧。

我有一个form 和一个<input type=date />,其min 属性因当前日期而异。我有这个JS例程来确定当前日期然后修改input type=date

let today = new Date();
let day = today.getDate();
let month = today.getMonth()+1;
let year = today.getFullYear();

today = year + '-' + month + '-' + day;

console.log(today)

const calendarInput = document.getElementById('to-do-date');
calendarInput.min = today;

当我检查 Chrome 的 Elements Console 时,我的 input 标签看起来像这样

<input type="date" id="to-do-date" name="to-do-date" min="2020-8-31" required> <!-- That's date that I'm writing this-->

很简单,对吧?

但是当我在我的form 上转到我的表单以输入实际日期时,我得到了这个

Input's calendar not graying out previous dates

在图片中,您可以看到我的日历没有将我的 min 属性之前的日期灰显,就像今天一样,2020-08-31,即使我明确声明要采用今天的日期并将其作为min 属性和我使用了不同的验证方法来防止用户输入过去的日期但无济于事。

如果你们知道这背后的原因并分享出来,我将不胜感激。

谢谢

【问题讨论】:

    标签: html date input attributes min


    【解决方案1】:

    发生这种情况是因为您需要具有“yyyy-mm-dd”格式,但现在您具有“yyyy-m-d”格式。所以你需要添加一个小函数,它会更正你的日期:

    const correctDate = (date) => date < 10 ? '0' + date : date;
    
    today = year + '-' + correctDate(month) + '-' + correctDate(day);
    

    希望对你有所帮助!

    【讨论】:

    • 是的!有用。谢谢你。我完全错过了检查实际格式。
    【解决方案2】:

    尝试使日期格式为YYYY-MM-DD 所以不是2020-8-31,而是2020-08-31

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-03
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多